29

我想了解如何从 MS SQL 数据库中获取具有标识列的所有表的列表。

4

5 回答 5

54
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]
);
于 2013-04-16T18:08:13.963 回答
8
      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
于 2014-08-01T16:36:36.760 回答
5

我喜欢这种方法,因为它使用联接而不是 WHERE EXISTS 或对 COLUMNPROPERTY 的调用。请注意,仅当您 a) 具有包含多个 IDENTITY 列的表并且 b) 不希望重复结果时,才需要 group by:

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;
于 2014-11-06T19:56:43.910 回答
1

下面的脚本将执行以下操作:

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 
于 2017-12-06T17:26:05.753 回答
-1

选择 OBJECT_NAME(object_Id) Rrom sys.identity_columns 其中 is_identity = 1;

于 2017-11-25T10:33:38.437 回答