views:

2337

answers:

6

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

Results would be something like:

TableName, ColumnName

+4  A: 

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
kcrumley
That's exactly what I was looking for. thanks!
Note: this works for me in SQL 2008, whereas the accepted answer does not (the question asks for SQL 2005).
Daniel Schaffer
+1  A: 

In SQL 2005:

select object_name(object_id), name
from sys.columns
where is_identity = 1
Euro Micelli
A: 

I think this works for SQL 2000:

SELECT 
    CASE WHEN C.autoval IS NOT NULL THEN
     'Identity'
    ELSE
     'Not Identity'
    AND
FROM
    sysobjects O
INNER JOIN
    syscolumns C
ON
    O.id = C.id
WHERE
    O.NAME = @TableName
AND
    C.NAME = @ColumnName
brian
kcrumley
Brimstedt
A: 

This query seems to do the trick:

SELECT 
    sys.objects.name AS table_name, 
    sys.columns.name AS column_name
FROM sys.columns JOIN sys.objects 
    ON sys.columns.object_id=sys.objects.object_id
WHERE 
    sys.columns.is_identity=1
    AND
    sys.objects.type in (N'U')
Manrico Corazzi
+1  A: 

Another way (for 2000 / 2005):

IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
    PRINT 'Yes'
ELSE
    PRINT 'No'
+7  A: 

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 TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
DaveCrawford