在 SQL Server 2005 上使用此 SQL
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME=@ColumnName
我得到主键和外键。
我怎样才能只获得外键?如何查看约束是主键还是外键?
谢谢
在 SQL Server 2005 上使用此 SQL
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME=@ColumnName
我得到主键和外键。
我怎样才能只获得外键?如何查看约束是主键还是外键?
谢谢
在这里找到了一个更优雅的解决方案
为了完整起见,在下面添加了代码,但所有功劳归于 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
将此添加为附加答案,因为它与我之前的答案相去甚远:)
我将以下 SQL 与 SQL Server 2005 一起使用以通过主键获取约束名称:
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)
通过外键获取约束名称:
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)
这取决于您的 DBMS,但约束应该在某处具有目标表和列。
如果是外键约束,则目标表与当前表不同。尝试
select *
代替
select constraint_name
查看您可以使用的所有神奇列。
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME=@ColumnName
AND REFERENCED_COLUMN_NAME IS NOT NULL
这不是最优雅的解决方案,但 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'”。错误。
我使用类似的东西。它也适用于 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
这一切都在系统表和视图中,这些都有很好的记录。