我想学习如何从MS SQL数据库中获取具有标识列的所有表的列表。
答案 0 :(得分:43)
SELECT
[schema] = s.name,
[table] = t.name
FROM sys.schemas AS s
INNER JOIN sys.tables AS t
ON s.[schema_id] = t.[schema_id]
WHERE EXISTS
(
SELECT 1 FROM sys.identity_columns
WHERE [object_id] = t.[object_id]
);
答案 1 :(得分:7)
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
答案 2 :(得分:4)
我喜欢这种方法,因为它使用连接而不是WHERE EXISTS或对COLUMNPROPERTY的调用。请注意,仅当a)具有多个IDENTITY列的表并且b)不希望重复结果时才需要分组:
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;
答案 3 :(得分:0)
以下脚本将执行:
SELECT a.name as TableName,
CASE WHEN b.name IS NULL
THEN 'No Identity Column'
ELSE b.name
END as IdentityColumnName
FROM sys.tables a
LEFT JOIN sys.identity_columns b on a.object_id = b.object_id
答案 4 :(得分:-1)
选择OBJECT_NAME(object_Id)Rrom sys.identity_columns 其中is_identity = 1;