26 May,2023 by Tom Collins
Question: How can I find tables in a SQL Server database that have a Primary Key ?
Answer: To identify if a table has a Primary Key - you can use the OBJECTPROPERTY method with the property TableHasPrimaryKey. This returns 1 or 0 depending on whether the table has a PRIMARY KEY or not .
Example 1 : Check if a table has a PRIMRY KEY
SELECT OBJECTPROPERTY(OBJECT_ID(N'myschema.myTable'),'TableHasPrimaryKey')
Example 2: Find all tables with Unique NonClustered Indexes and the table has no Primary Key
select schema_name(t.schema_id) as schemaname,t.name as tablename,i.name as indexname,i.is_unique from sys.indexes i, sys.tables t where i.object_id = t.object_id and i.type_desc = 'NONCLUSTERED' and i.is_unique = 1 and OBJECTPROPERTY(OBJECT_ID(N''+schema_name(t.schema_id)+'.'+t.name+''),'TableHasPrimaryKey') = 0
Example 3 : Find all tables with Primary Keys
SELECT SCHEMA_NAME(schema_id) AS schemaname, name AS tablename FROM sys.tables WHERE OBJECTPROPERTY(object_id,'TableHasPrimaryKey') = 1 GO
read more about SQL Server object management
List Foreign Keys referencing tables in SQL Server
What are the triggers in SQL Server
How to find all identity columns in SQL Server
How to find default values of all SQL Server columns
How to find computed columns on a SQL Server table
How to List all indexes of all SQL tables
How to find SQL Filtered Indexes
Find LOB tables with no PRIMARY KEY
How to find UDT on SQL Server columns?
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
Posted by: |