我如何知道CONSTRAINT_NAME是主键还是外键?

时间:2009-02-17 05:35:20

标签: sql sql-server metadata constraints table-structure

在SQL Server 2005上使用此SQL

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_NAME = @TableName
  AND COLUMN_NAME=@ColumnName

我获得了主键和外键。

我怎样才能获得外键? 如何查看约束是主键还是外键?

由于

6 个答案:

答案 0 :(得分:2)

找到了一个更优雅的解决方案here

下面添加的代码是为了完整性,但所有功劳都归功于Pinal Dave

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
LEFT JOIN sys.foreign_key_columns AS fc
   ON f.OBJECT_ID = fc.constraint_object_id

如果您只想要主键......

SELECT i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
        INNER JOIN sys.index_columns AS ic
        ON i.OBJECT_ID = ic.OBJECT_ID 
    AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1

添加了这个作为额外的答案,因为它已经从我之前的一个删除了:)

答案 1 :(得分:2)

我在SQL Server 2005中使用以下SQL来获取主键的约束名称:

SELECT Constraint_Name 
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
WHERE UNIQUE_CONSTRAINT_NAME = 
   (SELECT CONSTRAINT_NAME 
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
    WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName)

通过Foreing Key获取Constraint Name:

SELECT CONSTRAINT_NAME 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName

通过约束名称获取外键的表和字段:

SELECT TABLE_NAME, COLUMN_NAME 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE CONSTRAINT_NAME = @ConstraintName

按约束名称获取主键的表和字段:

SELECT TABLE_NAME, COLUMN_NAME 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE CONSTRAINT_NAME = 
    (SELECT UNIQUE_CONSTRAINT_NAME 
     FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
     WHERE CONSTRAINT_NAME = @ConstraintName)

答案 2 :(得分:0)

这取决于您的DBMS,但约束应该在某处具有目标表和列。

如果是外键约束,则目标表将与当前表不同。尝试

select *

而不是

select constraint_name

查看您可以使用的所有神奇列。

答案 3 :(得分:0)

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
  AND COLUMN_NAME=@ColumnName
  AND REFERENCED_COLUMN_NAME IS NOT NULL

答案 4 :(得分:0)

这不是最优雅的解决方案,但MS SQL Server使用PK&密钥的FK前缀命名约定,因此您可以使用类似......

的内容
SELECT CONSTRAINT_NAME 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_NAME = @TableName
AND LEFT(CONSTRAINT_NAME,2) = 'FK'

如果那是你的DBMS:)

修改

当我尝试Quassnoi的回答时,我收到了“无效的列名称'REFERENCED_COLUMN_NAME'。”错误。

答案 5 :(得分:0)

我使用类似的东西。它也适用于SQL Server 2000。

select  object_name(fkx.constid) as fk_name,
        fkx.keyno as num,
        object_name(fkx.fkeyid) as child_table,
        col_name(fkx.fkeyid, fkx.fkey) as child_column,
        object_name(fkx.rkeyid) as parent_table,
        col_name(fkx.rkeyid, fkx.rkey) as parent_column
from sysforeignkeys fkx
order by fk_name, fkx.keyno

所有这些都在系统表和视图中进行了很好的记录。