I want to get all the information about a table.
Like tableName, columnName , InPrimaryKey , Is UniqueKey , Is Identity , Datatype, Maxlength, Is ForiegnKey
by using inbuilt api of SQL SERVER like information_schema.columns
You could start with:
EXEC sp_help 'dbo.tablename';
Then you could look at the columns directly:
SELECT
c.name,
[type] = t.name,
c.max_length,
c.[precision],
c.[scale],
c.is_nullable,
c.is_identity
FROM sys.columns AS c
INNER JOIN sys.types AS t
ON c.system_type_id = t.system_type_id
AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = OBJECT_ID('dbo.tablename');
Indexes and participation in PK & unique constraints, foreign keys etc. are a little more complex, since multiple columns can participate in any of these entities. Here are indexes and PK/UQ constraints:
SELECT
[index] = i.name,
i.type_desc,
i.is_unique,
i.is_primary_key,
i.is_unique_constraint,
c.name,
ic.is_included_column
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.[object_id] = ic.[object_id]
INNER JOIN sys.columns AS c
ON ic.[object_id] = c.[object_id]
AND ic.index_id = i.index_id
AND ic.column_id = c.column_id
WHERE i.[object_id] = OBJECT_ID('dbo.tablename');
And then you could move on to foreign keys by looking at sys.foreign_keys and sys.foreign_key_columns. This is even more convoluted than above - are you looking for all the foreign keys of the current table that point at other tables, all the foreign keys in other tables that point at this one, or both?
Use SQL Server Management Objects (SMO). This is a convenient and fully managed API to get and manipulate the schema of a SQL Server database.
You can do a
select * from table where 0 = 1
into a data-table. The columns will be copied and are ready to be inspected.
If you want a working project, my stored procedure generator / class object creator reads the database schema for all tables and views in a database.
The code is available at http://radstudio.codeplex.com
The file called DataClassBuilder.Net.dll contains a method called LoadDatabaseSchema() and LoadDataFieldsSchema() should give you all the information you need about the data.
Related
My database is designed in SQL Server & I want get output in asp.net, LINQ, C#
I have 2 tables linked to 1 table (1:1)
My question is can I get a primary key linked to which table?
For example:
tbl_Document (ID, Date, ...)
tbl_Factor (ID, DocID, ...)
tbl_Finance (ID, DocID, ...)
What is the best way to know ID in tbl_Document linked to which table?
I can add record in tbl_Document as 'whichTable' and write the name of table in every column, and every time I want to search set "if" and check 'WhichTable'.
Is there a better way to do that?
Thanks, and sorry for my bad English :)
By default, you can get only all tables that have foreign key constraints to the parent table:
select object_name(f.referenced_object_id) pk_table, c1.name pk_column_name,
object_name(f.parent_object_id) fk_table, c2.name fk_column_name
from
sys.foreign_keys f
join sys.columns c1 on c1.object_id = f.referenced_object_id
join sys.columns c2 on c2.object_id = f.parent_object_id
join sys.foreign_key_columns k
on (k.constraint_object_id = f.object_id
and c2.column_id = k.parent_column_id
and c1.column_id = k.referenced_column_id )
where object_name(f.referenced_object_id) ='tbl_Document'
There is no such additional information regarding every particular row in parent table. It would be a duplicate information (since you can figure out it by searching in every child table). Thus, as you mentioned you can store child table name in the additional column and then as an option, construct sql dynamically to query child row.
(SQLite and C#)
I have this little problem. See those 2 tables. 1. is parent, 2. is child
I should get "broj_goluba" from parent table to match "par_m" and "par_z" in child table and later just display it in datagridview.
Foregin keys should help to get things done fast, but here when I write code I have much more lines of code opposed to not using foreign keys.
Could someone please help me and write down how my code (EDIT: SQL query) should look like when using foreign keys.
What I understand you need is that, but it doesn't have to do anything with speed. Maybe you mean INDEX and not FOREIGN KEY.
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M OR TABLE1.ID = TABLE2.PAR_J)
Or maybe you need BOTH values to be equal:
SELECT BROJ_GOLUBA
FROM TABLE1
INNER JOIN TABLE2 ON (TABLE1.ID = TABLE2.PAR_M AND TABLE1.ID = TABLE2.PAR_J)
Foreign keys don't exist to "help to get things done fast". They exist to enforce data integrity. Frankly, I don't see how the number of lines of T-SQL code you write is dependent on whether or not foreign keys exist.
The following query stub should help get you started on your query:
Select Table1.broj_goluba, Table2.par_z ...
From Table1
Inner Join Table2 on Table1.ID = Table2.par_m
I have now created a MySQL database for a POS-like system, and i am working with subtypes to put some different types in my database.
CREATE TABLE Product(
Prod_id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(40),
Barcode INT
);
CREATE TABLE Card(
Prod_id INT,
Price DECIMAL(8, 2),
FOREIGN KEY (Prod_id) REFERENCES Product(Prod_id)
);
CREATE TABLE Weapon(
Prod_id INT,
Caliber_id INT,
FOREIGN KEY (Prod_id) REFERENCES Product(Prod_id)
);
When i scan a barcode, i want to query the database. When a product is found, i want to display all information about it on the screen. I'm using a DataTable in C#, and with every result, i add a DataRow to the DataTable.
So i have 2 questions:
How can i neatly query the database, returning all information i have about a barcode?
How do i display this information in an efficiƫnt way on my screen?
I am assuming you are using only the mentioned tables
Please find the below sql statement which will return all the information as required
Select p.Prod_id,p.Name,p.Barcode,c.Price, w.Caliber_id
from Product p
inner join Card c
on
(
p.Prod_id = c.Prod_id
)
inner join Weapon w
on
(
p.Prod_id = w.Prod_id
)
where p.Barcode = 'Barcode'
if you have some products which does not in card or weapon you can use left outer joins
hope this will help you.
The database for my application contains tables (not editable by the user) that are necessary for my application to run. For instance, there is a Report table containing a list of my SSRS reports.
Except for the Auto-Increment and GUID fields, the data in my Report Table should match across all databases.
To keep existing client databases in synch with the ones created from scratch, there is a database updater app that runs scripts to update the existing client base.
There are Unit Tests to ensure Reports run correctly on both types of databases. However, other than developer eye, there is no system check to ensure the rows and values in those rows match among the tables. This is prone to human error.
To fix, I plan to add a small report to Unit Test report that will inform development of the following:
Records missing from the "Made From Scratch" database that exist in the "Updated" Database
Records missing from the "Updated" database that exist in the "Made From Scratch" Database
Fields that do not match between the tables
So far, I have a query to report the above information for all tables involved.
A sample query would look something like this:
--Take the fields I want to compare from TableToCompare in MadeFromScratch and put them in #First_Table_Var
--NOTE: MyFirstField should match in both tables in order to compare the values between rows
DECLARE #First_Table_Var table(
MyFirstField Varchar(255),
MySecondField VarChar(255),
MyThirdField Varchar(255),
);
INSERT INTO #First_Table_Var
SELECT
r.MyFirstField,
r.MySecondField,
l.MyThirdField
FROM
MadeFromScratch.dbo.TableToCompare r
INNER JOIN MadeFromScratch.dbo.LookUpTable l ON r.ForeignKeyID = l.PrimaryKeyID
--Take the fields I want to compare from TableToCompare in UpdatdDatabase and put them in #Second_Table_Var
DECLARE #Second_Table_Var table(
MyFirstField Varchar(255),
MySecondField VarChar(255),
MyThirdField Varchar(255),
);
INSERT INTO #Second_Table_Var
SELECT
r.MyFirstField,
r.MySecondField,
l.MyThirdField
FROM
UpdatdDatabase.dbo.TableToCompare r
INNER JOIN UpdatdDatabase.dbo.LookUpTable l ON r.ForeignKeyID = l.PrimaryKeyID
--**********************
-- CREATE OUTPUT
--**********************
--List Rows that exist in #Second_Table but not #First_Table
--(e.g. these rows need to be added to the table in MadeFromScratch)
SELECT
Problem = '1 MISSING ROW IN A MADE-FROM-SCRATCH DATABASE',
hur.MyFirstField,
hur.MySecondField,
hur.MyThirdField
FROM
#Second_Table_Var hur
WHERE
NOT EXISTS
(SELECT
*
FROM
#First_Table_Var hu
WHERE
hu.MyFirstField = hur.MyFirstField
)
UNION
--List Rows that exist in #First_Table but not #Second_Table
--(e.g. these rows need to be added to the table in UpdatdDatabase)
SELECT
Problem = '2 MISSING IN UPDATE DATABASE',
hur.MyFirstField,
hur.MySecondField,
hur.MyThirdField
FROM
#First_Table_Var hur
WHERE
NOT EXISTS
(SELECT
*
FROM
#Second_Table_Var hu
WHERE
hu.MySecondField = hur.MySecondField
)
UNION
--Compare fields among the tables where MyFirstField matches, but
SELECT
Problem = '3 MISMATCHED FIELD',
h.MyFirstField,
MySecondField = CASE WHEN h.MySecondField = hu.MySecondField THEN '' ELSE 'Created Value: ' + h.MySecondField + ' Updated Value: ' + hu.MySecondField END,
MyThirdField = CASE WHEN h.MyThirdField = hu.MyThirdField THEN '' ELSE 'Created Value: ' + CAST(h.MyThirdField AS VARCHAR(4)) + ' Updated Value: ' + CAST(hu.MyThirdField AS VARCHAR(4)) END,
FROM
#First_Table_Var h
INNER JOIN #Second_Table_Var hu on h.MyFirstField = hu.MyFirstField
WHERE
NOT EXISTS
(SELECT
*
FROM
#Second_Table_Var hu
WHERE
hu.MyFirstField = h.MyFirstField and
hu.MySecondField = h.MySecondField and
hu.MyThirdField = h.MyThirdField and
)
ORDER BY Problem
I won't have any problem writing code to parse through the results, but this methodology feels antiquated for the following reasons:
Several queries (which essentially do the same thing) will need to be written
Maintenance for this process can get cumbersome
I would like to be able to write something where the list of tables and fields to compare is maintained by some kind of file (XML?). So, whether fields are added or changes all the user has to do is update this file.
Is there a way to use LINQ and/or Reflection (or any feature in .NET 4.0 for that matter) where I could compare tables between two databases and maintain them like I've listed above?
Ideas are welcome. Ideas with an example would be great! :D
you said "Except for the Auto-Increment and GUID fields, the data in my Report Table should match across all databases."
I assume that these fields are ID fields, ideally, replication of the database should replicate the id fields too ensuring this will allow you to check for new inserts by ID, in case of updates, you can set a timestamp field for comparison.
How do I turn this table:
+------------+-----------------+
| Category + Subcategory |
+------------+-----------------+
|Cat..........+ Persian.........|
|Cat..........+ Siamese........|
|Cat..........+ Tabby...........|
|Dog.........+ Poodle..........|
|Dog.........+ Boxer............|
+------------+----------------+
on it's side to get the following:
+------------+-----------------+
| Cat......... + Dog............. |
+------------+-----------------+
+ Persian..+ Poodle.........+
+ Siamese + Boxer...........+
+ Burmese + ...................+
+------------+-----------------+
The initial table is from the following MySQL query:
select c.CATEGORYNAME, sc.NAME from subcategorydefinition sc
join categorydefinition c on sc.CATEGORYID = c.CATEGORYID
where c.ISDELETED = 0
order by CATEGORYNAME, NAME ASC
And I want to display it in (probably) a Gridview.
Cheers!
Pivot is static in SQL. You need to know in advance the columns you want in output, so if the list of categories is not fixed, you can't use pivot directly.
If you were using Microsoft SQL Server (which I know you're not, but it's for the sake of example), you could use a dynamic query in a stored procedure, as described here:
http://www.simple-talk.com/community/blogs/andras/archive/2007/09/14/37265.aspx
Now, in MySql, there is no way to execute dynamic SQL on the sql side (no equivalent of EXECUTE or sp_executeqsl), so your best choice would be to generate a similar SQL query server-side (aspnet server-side).
Another simpler idea IMHO would be to forget about doing it in SQL, but to do the aggregation in your C# code.
You should use pivot
To do this in SQL, you'd need to dynamically generate your query based on the available set of values in the "Category" column. This is usually fairly painful and error prone, regardless of whether you do it in pure SQL (in a sproc) or in code (dynamic SQL).
I'd recommend reading your values from the database in the way that they are stored, then dynamically creating a DataTable or similar structure to use as the datasource for your UI.
I don't have a working version of MySql handy but this will work as long as there is always more cats than dogs because of the left join at the end of the script. I forgot that there isn't a full outer join in MySql but you could use this logic to try it out.
But the point of this is that if you have two tables with arbitrary keys you can join on the keys to get the results lined up like you want.
-- drop tables
DROP TABLE dbo.cat
DROP TABLE dbo.dog
--create dog table
create table dog (
dog_id int IDENTITY(1,1) NOT NULL
,dog varchar(50)
)
--add dogs only
insert into dog (dog)
select subcategory
FROM play.dbo.test
where category = 'Dog'
--create cat table
create table cat (
cat_id int IDENTITY(1,1) NOT NULL
,cat varchar(50)
)
--add cats only
insert into cat (cat)
select subcategory
FROM play.dbo.test
where category = 'cat'
-- disply everything
SELECT cat
, dog
from dog d
--full outer join cat c
left join dog d
on d.dog_id = c.cat_id