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, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Pankaj Singh said...

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

DigviJay said...

exec sp_columns 'your tablename'