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.


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

2 comments:

Pankaj Singh said...

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

DigviJay said...

exec sp_columns 'your tablename'