问题
Trying to figure out a SQL script to test the existence of primary keys in cerain tables. If the table has no primary key, then the script should output the table name.
Tables to test:
TableA
TableB
TableC
After running the script (and lets say TableA and TableC have PKs, but not TableB), then the output would be below:
NoKeys
TableB
回答1:
;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:
I don't have the exact/complete code for you, but here's the idea:
You'll need to loop through your list of tables in the database:
SELECT *
FROM information_schema.tables`
The code to check if a Primary Key exists for your table would be something like:
SELECT *
FROM information_schema.table_constraints
WHERE constraint_type = 'PRIMARY KEY'
AND table_name = @Your_Table_Name`
回答3:
Returns 0 if no primary key, Returns 1 if there is a primary key
SELECT OBJECTPROPERTY(OBJECT_ID(N'MyTable'),'TableHasPrimaryKey')
回答4:
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`)
回答5:
I liked Sean's answer and it worked for me. You can add the clause
WHERE t.TABLE_TYPE = 'BASE TABLE'
just before the EXCEPT statement if you don't want to also get views back.
;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
来源:https://stackoverflow.com/questions/13258297/a-script-to-test-existence-of-primary-keys