How to get list of all tables that has identity columns

前端 未结 5 786
小蘑菇
小蘑菇 2021-02-04 00:21

I would like to learn how to fetch list of all tables that has identity columns from a MS SQL database.

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 00:48

    I like this approach because it uses a join instead of a WHERE EXISTS or a call to COLUMNPROPERTY. Note that the group by is only necessary if you a) have tables with more than one IDENTITY column and b) don't want duplicate results:

    SELECT 
        SchemaName = s.name,
        TableName = t.name
    FROM
        sys.schemas AS s
        INNER JOIN sys.tables AS t ON s.schema_id = t.schema_id
        INNER JOIN sys.columns AS c ON t.object_id = c.object_id
        INNER JOIN sys.identity_columns AS ic on c.object_id = ic.object_id AND c.column_id = ic.column_id
    GROUP BY
        s.name,
        t.name
    ORDER BY
        s.name,
        t.name;
    

提交回复
热议问题