If you ever need to find out whether a database has any tables that don’t have a primary key, you can run any of the following scripts in SQL Server to return just those tables.
All of these scripts take advantage of the OBJECTPROPERTY()
function. This function accepts a TableHasPrimaryKey
argument that you can check for a value of 0
. If it’s 0
, the table doesn’t have a primary key. If it’s 1
it does. Therefore, you can also use this function to return all tables with a primary key.
These scripts simply return the name of the table and its schema, but you can always modify them to return more columns.