1

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

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

上述附加列都与主键的标识、种子值、增量值等无关。

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

4

2 回答 2

5

更新

(现在使用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
于 2013-10-31T22:53:48.977 回答
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
于 2013-11-01T16:08:15.243 回答