Tuesday, 3 June 2014

Multiple ways to find all the tables that do not have a primary key?

METHOD 1 :
This is the shortest method to find all the tables that do not have a primary key. In this method, we need to use OBJECTPROPERTY to check each table property and filter it.
--This script is compatible with SQL Server 2005 and above.
USE AdventureWorks2012
GO
SELECT
  SCHEMA_NAME(schema_id) AS [Schema name]
, name AS [Table name]
FROM sys.tables
WHERE
OBJECTPROPERTY(object_id,'TableHasPrimaryKey') = 0
GO

METHOD 2 :
This is one of my favorite methods because I do not need to remember any other view name, I can browse all the data from sys.objects.
--This script is compatible with SQL Server 2005 and above.
USE AdventureWorks2012
GO
SELECT
  SCHEMA_NAME(schema_id) AS [Schema name]
, name AS [Table name]
FROM
sys.objects
WHERE [type]='U' AND object_id
NOT IN (
SELECT parent_object_id FROM sys.objects
WHERE [type]='PK'
)
GO




No comments:

Post a Comment