10

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

Tables to test:
TableA
TableB
TableC

运行脚本后(假设 TableA 和 TableC 有 PK,但没有 TableB),那么输出将如下所示:

NoKeys
TableB
4

6 回答 6

11

我没有适合您的确切/完整代码,但这是一个想法:

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

SELECT *  
FROM information_schema.tables

检查表是否存在主键的代码类似于:

SELECT *  
FROM information_schema.table_constraints  
WHERE constraint_type = 'PRIMARY KEY'   
AND table_name = @Your_Table_Name
于 2012-11-06T19:55:17.003 回答
10
;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
于 2012-11-06T20:01:56.523 回答
8

没有主键返回0,有主键返回1

SELECT OBJECTPROPERTY(OBJECT_ID(N'MyTable'),'TableHasPrimaryKey')
于 2019-02-27T21:59:26.073 回答
2

我的版本:

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

作为参考,请在此处查看 Microsoft 文档。

于 2021-03-30T13:46:41.243 回答
1

How about

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')
于 2012-11-06T19:59:18.273 回答
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
于 2016-11-01T00:06:55.063 回答