February 22, 2008

Find all tables in a database without a primary key




If you are performing a database audit and want to quickly find out the tables not having a primary key, use this query :

USE [Your DB]

GO
SELECT TABLE_SCHEMA as 'SCHEMA', TABLE_NAME as 'NO_Primary_Key'
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME NOT IN
( SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
) AND TABLE_TYPE = 'BASE TABLE'


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Find all tables in a database without a primary key"
  1. Megan said...
    April 18, 2010 at 3:15 AM

    How to use sys.objects to get the same info?

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions