Query to get all foreign key constraints in SQL Server 2000

前端 未结 3 813
生来不讨喜
生来不讨喜 2020-12-15 01:44

I need a query for SQL Server 2000 to get a list of all foreign keys.

Particularly all the foreign keys that point to a particular column.

How do I write thi

3条回答
  •  感情败类
    2020-12-15 02:13

    Look at the source of sp_helpconstraint for more ideas, but this should work...

    to get every FK that refers to target table & column

    • replace "YourTableName"
    • uncomment the last "AND" and set your target column name

    code:

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

提交回复
热议问题