Skip to content
iTecNote
  • Python
  • Javascript
  • PHP
  • Java
  • Android
  • iOS
  • jQuery
  • MySQL

Sql-server – How to determine what SQL Tables have an identity column programmatically

identity-columnmetadatasql-servertsql

I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.

Results would be something like:

TableName, ColumnName

Best Solution

Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:

select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME 

Related Solutions

Sql-server – How to check if a column exists in a SQL Server table

SQL Server 2005 onwards:

IF EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'columnName'
          AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
    -- Column Exists
END

Martin Smith's version is shorter:

IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END
Sql-server – Check if table exists in SQL Server

For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version.

To check if a table exists use:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    --Do Stuff
END
Related Question
  • Sql-server – Multiple Indexes vs Multi-Column Indexes
  • Sql – Insert results of a stored procedure into a temporary table
  • Sql-server – Altering a column: null to not null
  • Sql-server – How to change identity column values programmatically
  • Sql – Selecting COUNT(*) with DISTINCT
  • Sql – How to UPDATE from a SELECT in SQL Server
  • Sql – Find all tables containing column with specified name – MS SQL Server
  • Sql – Reset identity seed after deleting records in SQL Server