如何查找数据库中的所有主键及其标识和种子值?

时间:2013-10-31 22:45:13

标签: sql-server tsql sql-server-2012

以下查询返回所有数据库主键和其他列的列表。

SELECT  *
FROM    sysobjects AS s
WHERE   xtype='pk'

上述附加列均不与主键的标识,种子值,增量值等相关。

我应该使用什么查询,或者如何查找数据库中的所有主键及其身份和种子值?

2 个答案:

答案 0 :(得分:4)

<强>已更新

(现在使用identity_columns表而不是IDENT_...函数)

SELECT  object_name(i.object_id) tableName,
        i.name indexName,
        c.name columnName,
        c.is_identity,
        idc.seed_value,
        idc.increment_value,
        idc.last_value
FROM sys.indexes i
    INNER JOIN sys.index_columns ic ON  ic.object_id = i.object_id AND ic.index_id = i.index_id
    INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
    LEFT OUTER JOIN sys.identity_columns idc ON idc.object_id = c.object_id AND idc.column_id = c.column_id
WHERE i.is_primary_key = 1

答案 1 :(得分:1)

这是一个替代答案b / c我结合选择并添加了创建和修改日期的排序和模式名称,以便在模式之间使用b / c键名称是唯一的:

SELECT  schema_name = ( SELECT top 1 pk.CONSTRAINT_SCHEMA FROM information_schema.table_constraints pk INNER JOIN information_schema.key_column_usage c ON c.TABLE_NAME = pk.TABLE_NAME WHERE pk.CONSTRAINT_NAME like '%' + i.name + '%')
        ,object_name(i.object_id) tableName, i.name indexName, c.name columnName, c.is_identity 
        ,ident_seed(object_name(i.object_id)) seed
        ,ident_incr(object_name(i.object_id)) increment
        ,ident_current(object_name(i.object_id)) lastAssignedId
        ,CreateDate = ( SELECT s.crdate FROM sysobjects s INNER JOIN (SELECT COUNT(1) cnt, xtype FROM sysobjects group by xtype) c ON  s.xtype = c.xtype WHERE s.name = i.name)
        ,ModifiedDate = (SELECT s.refdate FROM sysobjects s INNER JOIN (SELECT COUNT(1) cnt, xtype FROM sysobjects group by xtype) c on  s.xtype = c.xtype WHERE s.name = i.name)
FROM    sys.indexes i
    INNER JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE   i.is_primary_key = 1 
ORDER BY    ModifiedDate, CreateDate DESC