用于测试主键是否存在的脚本

时间:2012-11-06 19:49:09

标签: sql sql-server sql-server-2005

试图找出一个SQL脚本来测试cerain表中是否存在主键。如果表没有主键,则脚本应输出表名。

Tables to test:
TableA
TableB
TableC

运行脚本后(假设TableA和TableC有PK,但不是TableB),那么输出将在下面:

NoKeys
TableB

6 个答案:

答案 0 :(得分:7)

我没有准确/完整的代码,但这里的想法是:

您需要遍历数据库中的表列表:

SELECT *  
FROM information_schema.tables`

检查表是否存在主键的代码如下:

SELECT *  
FROM information_schema.table_constraints  
WHERE constraint_type = 'PRIMARY KEY'   
AND table_name = @Your_Table_Name`

答案 1 :(得分:6)

;WITH tables_with_pk AS (
  SELECT t.table_schema, t.table_name  
  FROM INFORMATION_SCHEMA.TABLES t 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
      ON t.TABLE_NAME = tc.TABLE_NAME AND t.table_schema = tc.table_schema
  WHERE tc.constraint_type = 'PRIMARY KEY'
)
SELECT t.table_schema, t.table_name 
FROM INFORMATION_SCHEMA.TABLES t 
EXCEPT
SELECT table_schema, table_name
FROM tables_with_pk

答案 2 :(得分:1)

我的版本:

SELECT 1  
FROM SYS.KEY_CONSTRAINTS
WHERE [TYPE] = 'PK' AND [PARENT_OBJECT_ID] = OBJECT_ID('USER.USER');

作为参考检查 Microsoft 文档 here

答案 3 :(得分:0)

怎么样

USE information_schema;
SELECT `TABLE_NAME` FROM `TABLES` LEFT JOIN `TABLE_CONSTRAINTS` USING(`TABLE_SCHEMA`, `TABLE_NAME`) WHERE `TABLE_SCHEMA` = '__PUT_YOUR_DB_NAME_HERE__' AND `CONSTRAINT_NAME` LIKE '%PRIMARY%' AND ISNULL(`CONSTRAINT_CATALOG`)

答案 4 :(得分:0)

我喜欢肖恩的回答,这对我有用。您可以添加子句

WHERE t.TABLE_TYPE = 'BASE TABLE'

EXCEPT语句之前,如果您不想再获取视图。

;WITH tables_with_pk AS (
  SELECT t.table_schema, t.table_name
  FROM INFORMATION_SCHEMA.TABLES t 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
      ON t.TABLE_NAME = tc.TABLE_NAME AND t.table_schema = tc.table_schema
  WHERE tc.constraint_type = 'PRIMARY KEY' 
)
SELECT t.table_schema, t.table_name
FROM INFORMATION_SCHEMA.TABLES t 
WHERE t.TABLE_TYPE = 'BASE TABLE'
EXCEPT
SELECT table_schema, table_name
FROM tables_with_pk

答案 5 :(得分:0)

如果没有主键,则返回0, 如果有主键,则返回1

implementation "androidx.core:core-ktx:1.0.1"
implementation "androidx.appcompat:appcompat:1.0.2"
implementation "androidx.activity:activity-ktx:1.0.0-alpha04"