April 26, 2010

Find Tables with No Primary Key – SQL Server

Sometime back I had done a post called Find all tables in a database without a primary key where I used the INFORMATION_SCHEMA.TABLES.

Megan commented asking how to rewrite the same query using sys.objects. Well here it is!

USE NerdDinner;
name as [TableName], create_date
FROM sys.objects
WHERE type = 'U'
AND OBJECTPROPERTY([object_id], 'TableHasPrimaryKey') = 0;


No Primary Key

If you do not get any results, then all your tables in your database have primary keys

You may also want to check the following related posts written some time ago:

Find Primary Key of a SQL Server Table

List all the Non-Clustered Indexes in a SQL Server Database

Find out all the Primary Key and Foreign Key Constraints in a table

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


Jamorama said...

Hi, The above articles is very impressive, and I really enjoyed reading your blog and points that you expressed. I love to come back on a regular basis, pl. post more on the subject. Thanks.

Rocket Spanish said...

Thanks for providing such a nice post.
I liked your post and will definately link your blog in my website.
keep updating yourself.