Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to get the particular table structure

Author  Topic 

goodman2253
Yak Posting Veteran

88 Posts

Posted - 2012-03-21 : 02:22:13
Hi All,
I am stuck with an problem and i want your help.

Like in the database there are many tables and we can get the information through
select * from information_schema.columns

Can I get the table in structure like

TABLE_NAME---COLUMN_NAME----PK/FK----if FK then to which table



I have tried so far by using the combination of two
select * from information_schema.table_constraints
select * from information_schema.columns

But i didn't find the way

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-21 : 15:14:48
try something like


SELECT
c.TABLE_NAME,
c.COLUMN_NAME,
tc.CONSTRAINT_TYPE,
OBJECT_NAME(fkc.referenced_object_id) AS ReferencedTable,
COL_NAME(fkc.referenced_object_id,fkc.referenced_column_id) AS ReferencedColumn
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON c.COLUMN_NAME = kcu.COLUMN_NAME
AND c.TABLE_NAME = kcu.TABLE_NAME
AND c.TABLE_SCHEMA = kcu.TABLE_SCHEMA
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
ON tc.TABLE_NAME = c.TABLE_NAME
AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA
AND tc.CONSTRAINT_TYPE IN ('PRIMARY KEY','FOREIGN KEY')
LEFT JOIN sys.foreign_key_columns fkc
ON OBJECT_NAME(fkc.parent_object_id) = c.TABLE_NAME
AND COL_NAME(fkc.parent_object_id,fkc.parent_column_id)=c.COLUMN_NAME
WHERE c.TABLE_NAME='your table name here'


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-03-22 : 01:50:21
Why dont you try this?

EXEC sp_help table_name

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -