SQL Server信息_架构

时间:2019-09-06 10:36:05

标签: sql sql-server database-administration

我想通过SQL语句检查表的主键,我在下面的SQL中使用:

SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_NAME = 'T_ODSIN_DRG_BP_ROLE_DET'

但是我刚得到约束名称,但是我想查看主键中包含哪些列,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

只需加入INFORMATION_SCHEMA.KEY_COLUMN_USAGE即可:

IF OBJECT_ID('dbo.TestPKTable') IS NOT NULL
    DROP TABLE dbo.TestPKTable

CREATE TABLE dbo.TestPKTable (
    FirstPKColumn INT, 
    SecondPKColumn INT, 
    CONSTRAINT PK_TestPKTable PRIMARY KEY (FirstPKColumn, SecondPKColumn))

SELECT 
    PK.CONSTRAINT_NAME,
    PK.TABLE_CATALOG,
    PK.TABLE_SCHEMA,
    PK.TABLE_NAME,
    CU.COLUMN_NAME,
    CU.ORDINAL_POSITION
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS PK
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON 
        PK.CONSTRAINT_NAME = CU.CONSTRAINT_NAME AND
        PK.CONSTRAINT_CATALOG = CU.CONSTRAINT_CATALOG AND
        PK.CONSTRAINT_SCHEMA = CU.CONSTRAINT_SCHEMA
WHERE
    PK.CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY
    PK.CONSTRAINT_NAME,
    CU.ORDINAL_POSITION

结果:

CONSTRAINT_NAME     TABLE_CATALOG   TABLE_SCHEMA    TABLE_NAME  COLUMN_NAME     ORDINAL_POSITION
PK_TestPKTable      TestDB          dbo             TestPKTable FirstPKColumn   1
PK_TestPKTable      TestDB          dbo             TestPKTable SecondPKColumn  2