使用SQL Server 2005如何知道CONSTRAINT_NAME是主鍵還是外鍵?
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND [email protected]
這個SQL,我得到了主鍵和外鍵。
我怎樣才能得到外鍵? 如何查看約束是主鍵還是外鍵?
感謝
使用SQL Server 2005如何知道CONSTRAINT_NAME是主鍵還是外鍵?
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND [email protected]
這個SQL,我得到了主鍵和外鍵。
我怎樣才能得到外鍵? 如何查看約束是主鍵還是外鍵?
感謝
我用下面的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)
要通過Foreing重點得到約束名稱:
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
要獲取主鍵的表和字段由C onstraint名稱:
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 [email protected]
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」。「錯誤。
找到一個更好的解決方案here
代碼下面添加的完整性,但都歸功於皮納爾戴夫
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 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
這一切都在系統表和視圖,這是很好的記錄。
我使用SQL Server 2005 – 2009-02-17 11:09:39