使用SQL中的INFORMATION_SCHEMA.TABLE_CONSTRAINTS查找约束列名称

时间:2016-09-16 16:23:40

标签: sql-server database sql-server-2005 sql-server-2012 sql-server-2008-r2

我在表中设置了主键约束 - “tCustomerSessions”,名称为“PK_tCustomerSessions”。

以下是我的查询 -

SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'tCustomerSessions'
    AND Constraint_Type = 'PRIMARY KEY'

这里我如何获得已设置主键约束的列的名称?

1 个答案:

答案 0 :(得分:1)

SELECT
    tc.CONSTRAINT_NAME
  , ccu.COLUMN_NAME
FROM
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
    JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu ON ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
    tc.TABLE_NAME = 'tCustomerSessions'
    AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'