how to get table structure with column name in a single row? - sql

Can anyone help me with the query to get table name,column name , column datatype , isprimary etc in single row .
for eg:
My output of employee table with Columns E_Id,E_Name,E_City should be as below
TabName ColumnName datatype isprimary Columnname datatype isprimary Columnname datatype
Employee - E_Id - int - S - E_Name - varchar - N - E_City - varchar

You can use the INFORMATION_SCHEMA system views to get this information for any table.
The following is an example:
SELECT
c.TABLE_NAME,
c.COLUMN_NAME,
c.DATA_TYPE,
CASE WHEN tc.CONSTRAINT_NAME IS NOT NULL THEN 1 ELSE 0 END AS IsPrimary
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
AND tc.CONSTRAINT_SCHEMA = ccu.CONSTRAINT_SCHEMA
AND tc.CONSTRAINT_CATALOG = ccu.CONSTRAINT_CATALOG
AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
)
ON ccu.COLUMN_NAME = c.COLUMN_NAME
AND ccu.TABLE_NAME = c.TABLE_NAME
AND ccu.TABLE_SCHEMA = c.TABLE_SCHEMA
AND ccu.TABLE_CATALOG = c.TABLE_CATALOG
WHERE c.TABLE_NAME = 'Employee'

You can get table schema from the following,
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLENAME';
GO
(but the output format is not like you want)
source: http://technet.microsoft.com/en-us/library/ms186778.aspx

Related

Update table with matching primary keys

I have two tables TABLE1 and TABLE2.
I need to update TABLE1 with the matching primary keys from TABLE2.
Here is my code to get the primary key from TABLE1:
SELECT C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C ON C.CONSTRAINT_NAME = T.CONSTRAINT_NAME
WHERE C.TABLE_NAME = 'TABLE1'
AND T.CONSTRAINT_TYPE = 'PRIMARY KEY'
This is the code to get primary key for TABLE2:
SELECT C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C ON C.CONSTRAINT_NAME = T.CONSTRAINT_NAME
WHERE C.TABLE_NAME = 'TABLE2'
AND T.CONSTRAINT_TYPE = 'PRIMARY KEY'
And this code is used to update TABLE1:
MERGE INTO <TABLE1>
USING <TABLE2> ON (TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME)
WHEN MATCHED THEN
UPDATE
SET <TABLE1.COLUMN_NAME> = <TABLE1.COLUMN_NAME>
I need to merge all snippets of code to update the TABLE1, please help me how to get the primary keys and update with a single code.
As #GuidoG recommended, you will probably need to use dynamic SQL to perform this feat. Furthermore, from your question it is hard to figure out how to determine that Table1 and Table2 are related to one another.
Let us suppose that you have a table with table pairs available, and Table1 and Table 2 are one of those pairs. We'll need to figure out what the primary keys of both tables are, and then build the dynamic SQL using this information.
DECLARE #tableCombinations TABLE ([MainTable] NVARCHAR(255), [SubTable] NVARCHAR(255))
INSERT INTO #tableCombinations ([MainTable], [SubTable]) VALUES ('Table1','Table2')
DECLARE #q NVARCHAR(MAX) = ''
;WITH PrimaryKeys AS (
SELECT [Schema_Name] = sch.[name]
, [Table_Name] = tbl.[name]
, [Column_Name] = cols.[name]
FROM [sys].[indexes] i
JOIN [sys].[index_columns] ic ON i.[index_id] = ic.[index_id] AND i.[object_id] = ic.[object_id]
JOIN [sys].[columns] cols ON cols.[object_id] = ic.[object_id] AND cols.[column_id] = ic.[column_id]
JOIN [sys].[tables] tbl ON ic.[object_id] = tbl.[object_id]
JOIN [sys].[schemas] sch ON tbl.[schema_Id] = sch.[schema_id]
WHERE i.[is_primary_key] = 1
)
SELECT #q += 'MERGE INTO ' + QUOTENAME(pkMain.[Schema_Name]) + '.' + QUOTENAME(pkMain.[Table_Name]) +' mt
USING ' + QUOTENAME(pkSub.[Schema_Name]) + '.' + QUOTENAME(pkSub.[Table_Name]) + 'st ON (
mt.' + QUOTENAME(pkMain.[Column_Name]) + ' = st.' + pkSub.[Column_Name] + ')
WHEN MATCHED THEN UPDATE SET mt.' + QUOTENAME(pkMain.[Column_Name]) + ' = st.' + pkSub.[Column_Name] + ';' + CHAR(13) + CHAR(10)
FROM #tableCombinations tc
JOIN [PrimaryKeys] pkMain ON tc.[MainTable] = pkMain.[Table_Name]
JOIN [PrimaryKeys] pkSub ON tc.[SubTable] = pkSub.[Table_Name]
SET #q = REPLACE(#q, ' ', '')
SELECT #q
Of course, if this yields the correct results, you can directly execute this query using [sys].[sp_executesql]. For more reliable results, be sure to include the schema names of the table combinations.

Column Names from SQL Server

I am trying without success to get column names of my table in SQL Server.
I have tried the following:
SELECT * FROM [myDB].INFORMATION_SCHEMA.COLUMNS where [TABLE_NAME] = N'myTable'
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='myTable'
SELECT COLUMN_NAME , *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTable' AND TABLE_SCHEMA='dbo'
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE [Name] = 'myTable')
SELECT c.name FROM sys.columns c
INNER JOIN sys.tables t
ON t.object_id = c.object_id
AND t.name = 'myTable'
What is being returned is, what I think is, meta data of the table.
While in fact the actual column names are:
How can I return the column names from 'myTable'?
This solution returned the list I was looking for
SELECT name
FROM sys.columns
WHERE object_id = Object_id('myTable')

SQL - Finding FK details of column

I have some SQL that gets a few details about a table.
SELECT Column_Name, Is_Nullable, Data_Type, Character_Maximum_Length
FROM Information_Schema.Columns
WHERE Table_Name='GenSchool'
This is working ok so far and returns a row per column in the table. What I want however, is for it to also return some Foreign Key details too. For example, GenSchool has a column SchoolType which has a FK to GenSchoolType.Code.
As well as the columns selected above, I need the query to return the FK table and column name of linked table or NULL where the column doesn't have a FK.
This is returned from the query above.
Code NO nvarchar 10
CodeDescription YES nvarchar 80
Deleted NO bit NULL
Type NO nvarchar 20
And I'd like it to return something like
Code NO nvarchar 10 NULL NULL
CodeDescription YES nvarchar 80 NULL NULL
Deleted NO bit NULL NULL NULL
Type NO nvarchar 20 GenSchoolType Code
I've been trying for ages using inner joins on sys tables but I'm not getting anywhere. If you need me to show what I've tried I can.
Thank you in advance.
So I finally worked out the solution.
with fks as (
select fk.name AS 'FKName', o_p.name AS 'ParentNameTable',
c_p.name AS 'ParentNameColumn', o_r.name AS 'ReferencedNameTable',
c_r.name AS 'ReferencedNameColumn', fkc.*
from sys.foreign_key_columns fkc
inner join sys.foreign_keys fk on fk.object_id = fkc.constraint_object_id
inner join sys.objects o_p on o_p.object_id = fkc.parent_object_id
inner join sys.objects o_r on o_r.object_id = fkc.referenced_object_id
inner join sys.columns c_p on c_p.object_id = fkc.parent_object_id and c_p.column_id = fkc.parent_column_id
inner join sys.columns c_r on c_r.object_id = fkc.referenced_object_id and c_r.column_id = fkc.referenced_column_id
)
select c.Table_Name, c.Column_Name, c.Is_Nullable, c.Data_Type,
c.Character_Maximum_Length, COLUMNPROPERTY(OBJECT_ID(#table),
c.Column_Name,'IsIdentity') AS 'Is_Identity',
fks.FKName, fks.ReferencedNameTable, fks.ReferencedNameColumn
from information_schema.columns c
left join fks on c.Table_Name = fks.ParentNameTable and c.Column_Name = fks.ParentNameColumn
where c.table_name = #table
This returns a row per column in the database with the following data
Table Name
Column Name
Nullable
Data Type
Max Length
Identity
FK Name
Table Referenced
Column Referenced
Feel free to use this if it meets your needs.
Join to information_schema.REFERENTIAL_CONSTRAINTS:
SELECT Column_Name, Is_Nullable, Data_Type, Character_Maximum_Length, rc.REFERENCED_TABLE_NAME
FROM Information_Schema.Columns c
left join information_schema.REFERENTIAL_CONSTRAINTS rc on rc.TABLE_NAME = c.TABLE_NAME
WHERE Table_Name='GenSchool'
Here is a query from the MSDN page related to your query.
SELECT TABLE_NAME, CONSTRAINT_NAME , COLUMN_NAME , ORDINAL_POSITION
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE CONSTRAINT_NAME IN (
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS)
ORDER BY TABLE_NAME, ORDINAL_POSITION
did you try sp_fkeys
exec sp_fkeys <TableName>

SQL Server: Get table primary key using sql query [duplicate]

This question already has answers here:
How do you list the primary key of a SQL Server table?
(28 answers)
Closed 3 years ago.
I want to get a particular table's primary key using SQL query for SQL Server database.
In MySQL I am using following query to get table primary key:
SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'
What is equivalent of above query for SQL Server ?.
If There is a query that will work for both MySQL and SQL Server then It will be an ideal case.
I also found another one for SQL Server:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'
Found another one:
SELECT
KU.table_name as TABLENAME
,column_name as PRIMARYKEYCOLUMN
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
AND KU.table_name='YourTableName'
ORDER BY
KU.TABLE_NAME
,KU.ORDINAL_POSITION
;
I have tested this on SQL Server 2003/2005
Using SQL SERVER 2005, you can try
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN
sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored
but I am afraid I have no access to SQL to actually verify the same.
SELECT COLUMN_NAME FROM {DATABASENAME}.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '{TABLENAME}' AND CONSTRAINT_NAME LIKE 'PK%'
WHERE
{DATABASENAME} = your database from your server AND
{TABLENAME} = your table name from which you want to see the primary key.
NOTE : enter your database name and table name without brackets.
select *
from sysobjects
where xtype='pk' and
parent_obj in (select id from sysobjects where name='tablename')
this will work in sql 2005
The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!
SELECT DISTINCT
sys.tables.object_id AS TableId,
sys.columns.column_id AS ColumnId,
sys.columns.name AS ColumnName,
sys.types.name AS TypeName,
sys.columns.precision AS NumericPrecision,
sys.columns.scale AS NumericScale,
sys.columns.is_nullable AS IsNullable,
( SELECT
COUNT(column_name)
FROM
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
WHERE
TABLE_NAME = sys.tables.name AND
CONSTRAINT_NAME =
( SELECT
constraint_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = sys.tables.name AND
constraint_type = 'PRIMARY KEY' AND
COLUMN_NAME = sys.columns.name
)
) AS IsPrimaryKey,
sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = 'TABLE'
ORDER BY
IsPrimaryKey
You can use only the primary key part, but I think that the rest might become handy.
Best regards,
David
This should list all the constraints and at the end you can put your filters
/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME)
AS
(
SELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME='' ,
REFERENCE_COL_NAME=''
FROM sys.key_constraints as PKnUKEY
INNER JOIN sys.tables as PKnUTable
ON PKnUTable.object_id = PKnUKEY.parent_object_id
INNER JOIN sys.index_columns as PKnUColIdx
ON PKnUColIdx.object_id = PKnUTable.object_id
AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
INNER JOIN sys.columns as PKnUKEYCol
ON PKnUKEYCol.object_id = PKnUTable.object_id
AND PKnUKEYCol.column_id = PKnUColIdx.column_id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=PKnUTable.name
AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
CONSTRAINT_TYPE='FK',
PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,
REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30))
FROM sys.foreign_key_columns FKC
INNER JOIN sys.sysobjects oConstraint
ON FKC.constraint_object_id=oConstraint.id
INNER JOIN sys.sysobjects oParent
ON FKC.parent_object_id=oParent.id
INNER JOIN sys.all_columns oParentCol
ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
INNER JOIN sys.sysobjects oReference
ON FKC.referenced_object_id=oReference.id
INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
ON oParentColDtl.TABLE_NAME=oParent.name
AND oParentColDtl.COLUMN_NAME=oParentCol.name
INNER JOIN sys.all_columns oReferenceCol
ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
)
select * from ALL_KEYS_IN_TABLE
where
PARENT_TABLE_NAME in ('YOUR_TABLE_NAME')
or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx
Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.
this solution should work:
select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME'
AND TABLE_SCHEMA='DATABASENAME'
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys #table_server = N'server_name',
#table_name = N'table_name',
#table_catalog = N'db_name',
#table_schema = N'schema_name'; --frequently 'dbo'

SQL Server 2000 - Query a Table’s Foreign Key relationships

Nearly identical to Query a Table's Foreign Key relationships, but for SQL Server 2000
For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo.
SELECT o2.name
FROM sysobjects o
INNER JOIN sysforeignkeys fk on o.id = fk.rkeyid
INNER JOIN sysobjects o2 on fk.fkeyid = o2.id
WHERE o.name = 'foo'
Try this T-SQL:
select col_name(fkeyid, fkey) as column_name, object_name(rkeyid) as referenced_table_name, col_name(rkeyid, rkey) as referenced_column_name from sysforeignkeys where object_name(fkeyid) = 'tableNameHere' order by constid
I've rewritten the query slightly to give you all of the other tables that rely on a particular table:
select object_name(fkeyid),
col_name(fkeyid, fkey) as column_name,
col_name(rkeyid, rkey) as referenced_column_name
from sysforeignkeys
where object_name(rkeyid) = 'tableNameHere'
order by constid
Parents and children
/* this will find out all of the foreign key references for a table*/
DECLARE #tableName varchar(128)
SET #tableName = 'tCounter'
SELECT
pt.[name] AS 'parentTable',
ct.[name] AS 'childTable',
fk.[name] AS 'fkName',
*
FROM sys.foreign_keys fk
INNER JOIN sys.tables pt
ON pt.object_ID = fk.parent_object_id
INNER JOIN sys.tables ct
ON ct.object_ID = fk.referenced_object_id
WHERE pt.name = #tableName
OR ct.name = #tableName
ORDER BY pt.name, ct.name
Start here
SELECT cons.TABLE_NAME
, cons.CONSTRAINT_NAME PK_NAME
, cols.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons
LEFT join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cols
ON cons.CONSTRAINT_NAME = cols.CONSTRAINT_NAME
WHERE cons.CONSTRAINT_TYPE = 'foreign KEY'
ORDER BY cons.TABLE_NAME
, cons.CONSTRAINT_NAME
, cols.COLUMN_NAME
[edit] formatting is all messed up
[edit2] no longer