查询逻辑检查:计算否。 db中的主键

时间:2014-07-21 07:27:17

标签: sql sql-server

以下1,2和3的结果相同。只需要知道这个逻辑是否正确,两个查询都返回no的值。主键..

1

SELECT *
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id AND 

t.type = 'U'
LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T.[object_id]
where is_primary_key=1

2

SELECT COUNT(*) AS 'PRIMARY_KEY_CONSTRAINT'
FROM sys.objects
WHERE type_desc IN ('PRIMARY_KEY_CONSTRAINT')

3

 SELECT Count(*)
    FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE  CONSTRAINT_TYPE = 'PRIMARY KEY'

3 个答案:

答案 0 :(得分:0)

SELECT Count(*)
FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE  CONSTRAINT_TYPE = 'PRIMARY KEY' 

我认为这是更好的方法

答案 1 :(得分:0)

第三个查询是正确的。但是需要修改第二个查询以添加检查以排除SYS表。 sys.Objects有系统表(所以我们需要添加一个检查),而信息模式不包括系统表

2)

SELECT COUNT(*) AS 'PRIMARY_KEY_CONSTRAINT'
FROM sys.objects
WHERE type_desc IN ('PRIMARY_KEY_CONSTRAINT') AND is_ms_shipped <>1

3)

SELECT Count(*)
FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE  CONSTRAINT_TYPE = 'PRIMARY KEY' 

答案 2 :(得分:0)

希望这也可以帮助你。

SELECT  COUNT(*) [Ct_PK]
FROM    SYS.OBJECTS 
WHERE   TYPE = 'PK'