我需要获取数据库中所有外键的列表。此列表必须包括引用表和列、引用的表和列、约束名称以及(对于复合键)引用列在复合外键中的位置。
提前致谢,
另一种方式(包括字段的序数位置):
select
fk.CONSTRAINT_NAME
, fk.TABLE_NAME FK_Table
, kcu.COLUMN_NAME FK_Column
, ptc.TABLE_NAME PK_Table
, ptKcu.COLUMN_NAME PK_Column
, kcu.ORDINAL_POSITION
from
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
on rc.CONSTRAINT_NAME = fk.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
on rc.UNIQUE_CONSTRAINT_NAME = pk.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
on rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
inner join INFORMATION_SCHEMA.TABLE_CONSTRAINTS ptc
on pk.TABLE_NAME = ptc.TABLE_NAME
and ptc.CONSTRAINT_TYPE = 'PRIMARY KEY'
inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE ptKcu
on ptc.CONSTRAINT_NAME = ptKcu.CONSTRAINT_NAME
and kcu.ORDINAL_POSITION = ptKcu.ORDINAL_POSITION
--where
-- FK.TABLE_NAME = '<name of table containing foreign key>'
你可以试试这样(从这里): -
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
也看看这个