在SQL Server 2008中,我想获取主键跨越的列(列名)列表。
我试过了
SELECT *
FROM sys.key_constraints
LEFT JOIN sysconstraints ON (sys.key_constraints.object_id = sysconstraints.constid)
WHERE
type = 'PK'
AND parent_object_id = OBJECT_ID('dbo.permissioncache');
这将返回主键和其他一些值,但不返回PK列的完整列表。
我还要加入哪些其他表?
答案 0 :(得分:4)
试试这种方式
INFORMATION_SCHEMA
方法
SELECT TC.TABLE_NAME,
COLUMN_NAME,
TC.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cc
ON cc.Constraint_Name = tc.Constraint_Name
AND cc.Table_Name = tc.Table_Name
WHERE Constraint_Type = 'PRIMARY KEY'
AND cc.Table_Name = 'Yourtable'
Sys
选项,
SELECT t.name AS TABLE_NAME,
c.name AS COLUMN_NAME,
kc.name AS CONSTRAINT_NAME
FROM sys.key_constraints AS kc
JOIN sys.tables AS t
ON t.object_id = kc.parent_object_id
JOIN sys.index_columns AS ic
ON ic.object_id = t.object_id
AND ic.index_id = kc.unique_index_id
JOIN sys.columns AS c
ON c.object_id = t.object_id
AND c.column_id = ic.column_id
WHERE kc.type = 'PK'
AND t.name = 'Yourtable'
答案 1 :(得分:2)
SELECT Col.Column_Name
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
ON
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
WHERE Constraint_Type = 'PRIMARY KEY'
如果您想获取数据库中所有主键列的列表,那么
USE myDB;
GO
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
答案 2 :(得分:0)
使用内连接而不是左外连接,如果使用左外连接,它将给出左表中的所有行。