我需要查询SQL Server 2000以获取所有外键的列表。
特别是所有指向特定列的外键。
如何撰写此查询?
答案 0 :(得分:14)
select * from sysobjects
where xtype = 'F'
我应该这样做,并且与SQL Server 2000兼容,我希望!
如果您还需要SQL Server 2000中的表和列信息,它会更复杂一些;您需要加入sysforeignkeys
和syscolumns
目录视图,如下所示:
select
so.name 'foreign key name',
OBJECT_NAME(parent_obj) 'table',
OBJECT_NAME(sf.fkeyid) 'referencing table',
sc1.name 'referencing column',
OBJECT_NAME(sf.rkeyid) 'referenced table',
sc2.name 'referenced column'
from sysobjects so
inner join sysforeignkeys sf on so.id = sf.constid
inner join syscolumns sc1 on sf.fkeyid = sc1.id and sf.fkey = sc1.colid
inner join syscolumns sc2 on sf.rkeyid = sc2.id and sf.fkey = sc2.colid
where so.xtype in ('F','PK')
如果您想利用SQL Server 2000中确实可用的INFORMATION_SCHEMA视图,请使用此查询:
SELECT
rc.CONSTRAINT_NAME,
rcu.TABLE_NAME 'Referencing Table',
rcu.COLUMN_NAME 'Referencing Column',
rcu1.TABLE_NAME 'Referenced Table',
rcu1.COLUMN_NAME 'Referenced Column'
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE rcu
ON rc.CONSTRAINT_CATALOG = rcu.CONSTRAINT_CATALOG
AND rc.CONSTRAINT_NAME = rcu.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE rcu1
ON rc.UNIQUE_CONSTRAINT_CATALOG = rcu1.CONSTRAINT_CATALOG
AND rc.UNIQUE_CONSTRAINT_NAME = rcu1.CONSTRAINT_NAME
马克
答案 1 :(得分:4)
select * from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
如果您需要有关密钥的更多信息,则可以将其加入INFORMATION_SCHEMA.KEY_COLUMN_USAGE视图,该视图包含密钥引用的列。
答案 2 :(得分:1)
查看sp_helpconstraint的来源以获取更多想法,但这应该有效......
获取每个引用目标表的FK&柱
代码:
--list all tables & columns that refer to the given table
select
k.name,pt.Name AS ParentTable,pc.name,c.constraint_column_id,ct.Name AS ReferedToTable,c.referenced_column_id,cc.Name
from sys.foreign_keys k
INNER JOIN sys.foreign_key_columns c ON k.parent_object_id=c.parent_object_id
INNER JOIN sys.objects pt ON c.parent_object_id=pt.object_ID
INNER JOIN sys.objects ct ON c.referenced_object_id=ct.object_ID
INNER JOIN sys.columns pc ON c.parent_object_id=pc.object_ID AND c.parent_column_id=pc.column_id
INNER JOIN sys.columns cc ON c.referenced_object_id=cc.object_ID AND c.referenced_column_id=cc.column_id
where k.referenced_object_id = object_id('YourTableName')
--AND pc.name='YourColumnName' --parent table column name
--AND cc.name='YourColumnName' --referenced table's column name