我有一些SQL可以获得有关表的一些细节。
SELECT Column_Name, Is_Nullable, Data_Type, Character_Maximum_Length
FROM Information_Schema.Columns
WHERE Table_Name='GenSchool'
到目前为止这工作正常并且在表中每列返回一行。但是,我想要它也返回一些外键细节。例如,GenSchool
有一列SchoolType
,其FK为GenSchoolType.Code
。
除了上面选择的列,我需要查询返回链接表的FK表和列名,或者列没有FK的NULL。
这是从上面的查询中返回的。
Code NO nvarchar 10
CodeDescription YES nvarchar 80
Deleted NO bit NULL
Type NO nvarchar 20
我希望它返回类似
的内容Code NO nvarchar 10 NULL NULL
CodeDescription YES nvarchar 80 NULL NULL
Deleted NO bit NULL NULL NULL
Type NO nvarchar 20 GenSchoolType Code
我在sys
表上使用内部联接已经尝试了很长时间但是我没有到达任何地方。如果你需要我展示我尝试过的东西。
提前谢谢。
答案 0 :(得分:2)
所以我终于找到了解决方案。
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
这将在数据库中的每列返回一行,其中包含以下数据
如果满足您的需求,请随意使用。
答案 1 :(得分:1)
加入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'
答案 2 :(得分:1)
以下是与您的查询相关的MSDN页面中的查询。
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
答案 3 :(得分:1)
你试过sp_fkeys
吗?exec sp_fkeys <TableName>