February 26, 2008

Find all tables with or without an IDENTITY column




The SYS.IDENTITY_COLUMNS is a quiet a handy view. Doing a SELECT * FROM SYS.IDENTITY_COLUMNS will return you all the columns that are identity columns for the current database. The object_id information returned from the SELECT query can be used to return the table name and using this, we can in turn return all the tables that are IDENTITY columns.

To find all tables with IDENTITY Columns

USE [YOURDBNAME]
SELECT (SCHEMA_NAME(schema_id) + '.' + name) as SchemaTable
FROM sys.tables
WHERE [name] IN
(
SELECT OBJECT_NAME(OBJECT_ID) AS TABLENAME
FROM SYS.IDENTITY_COLUMNS
)
ORDER BY SchemaTable;
GO

To find all tables without IDENTITY Columns

USE [YOURDBNAME]
SELECT (SCHEMA_NAME(schema_id) + '.' + name) as SchemaTable
FROM sys.tables
WHERE [name] NOT IN
(
SELECT OBJECT_NAME(OBJECT_ID) AS TABLENAME
FROM SYS.IDENTITY_COLUMNS
)
ORDER BY SchemaTable;
GO

We could have used only the view to find out the tables with or without the identity columns. The sys.tables was used to get the schema as well.


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

2 Responses to "Find all tables with or without an IDENTITY column"
  1. Pankaj Singh said...
    May 21, 2010 at 6:18 AM

    thanks a lot......
    worked like a charm

  2. DigviJay said...
    May 16, 2012 at 5:01 AM

    exec sp_columns 'your tablename'

 

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