SQL Server 2000 - 查询表的外键关系

时间:2009-01-14 20:21:33

标签: sql sql-server database sql-server-2000 foreign-keys

Query a Table's Foreign Key relationships几乎完全相同,但对于SQL Server 2000

对于给定的表'foo',我需要一个查询来生成一组具有指向foo的外键的表。

4 个答案:

答案 0 :(得分:7)

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'

答案 1 :(得分:3)

试试这个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

我稍微重写了一下这个查询,为你提供了依赖特定表的所有其他表:

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

答案 2 :(得分:2)

父母和子女

/* 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

答案 3 :(得分:1)

从这里开始

    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]格式化全部搞砸了

[edit2]不再