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.

2 comments: