试图找出一个 SQL 脚本来测试 cerain 表中是否存在主键。如果表没有主键,那么脚本应该输出表名。
Tables to test:
TableA
TableB
TableC
运行脚本后(假设 TableA 和 TableC 有 PK,但没有 TableB),那么输出将如下所示:
NoKeys
TableB
试图找出一个 SQL 脚本来测试 cerain 表中是否存在主键。如果表没有主键,那么脚本应该输出表名。
Tables to test:
TableA
TableB
TableC
运行脚本后(假设 TableA 和 TableC 有 PK,但没有 TableB),那么输出将如下所示:
NoKeys
TableB
我没有适合您的确切/完整代码,但这是一个想法:
您需要遍历数据库中的表列表:
SELECT *
FROM information_schema.tables
检查表是否存在主键的代码类似于:
SELECT *
FROM information_schema.table_constraints
WHERE constraint_type = 'PRIMARY KEY'
AND table_name = @Your_Table_Name
;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
没有主键返回0,有主键返回1
SELECT OBJECTPROPERTY(OBJECT_ID(N'MyTable'),'TableHasPrimaryKey')
我的版本:
SELECT 1
FROM SYS.KEY_CONSTRAINTS
WHERE [TYPE] = 'PK' AND [PARENT_OBJECT_ID] = OBJECT_ID('USER.USER');
作为参考,请在此处查看 Microsoft 文档。
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')
我喜欢肖恩的回答,它对我有用。您可以添加子句
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