3

我正在尝试做这样的事情:

declare @myCurrentSeedValue int;
select @myCurrentSeedValue = DBCC CheckIdent('MyTable', NORESEED);

这显然是不正确的语法。有人对我如何做到这一点有任何建议吗?

我知道我可以做这样的事情:

select @myCurrentSeedValue = IDENT_SEED('MyTable');

但问题在于 IDENT_SEED 函数上的每个 MSDN:

使用 DBCC CHECKIDENT 更改标识列的当前值不会更改此函数返回的值。

这可能会有问题,因为我们有其他存储过程将调用 DBCC CHECKIDENT 并重新设置标识列的种子,因此我实际上需要当前种子而不是原始种子。

4

2 回答 2

12

使用Ident_current可以获取表的当前标识,无论哪个进程更新表标识。它适用于任何会话,任何范围。


declare @myCurrentSeedValue int;
select @myCurrentSeedValue = IDENT_CURRENT( 'MyTable' )
select @myCurrentSeedValue
于 2013-03-29T21:30:08.100 回答
0

IDENT_CURRENTDBCC CHECKIDENT如果根本没有填充表,则不会返回与显示相同的值。

对于刚刚创建的表DBCC CHECKIDENT('NewTable', NORESEED)输出当前标识为 NULL(即从未分配过):

检查身份信息:当前身份值“NULL”,当前列值“NULL”。

但是,IDENT_CURRENT('NewTable')返回1根据规格这是正确的:

当 IDENT_CURRENT 值为 NULL 时(因为表从未包含行或已被截断),IDENT_CURRENT 函数返回种子值。

1 IDENT_CURRENT当表中有单行时,返回相同的值。

要获得当前身份的正确值,您可以直接从sys.identity_columns表中获取此信息:

SELECT last_value
FROM sys.identity_columns
WHERE object_id = OBJECT_ID('NewTable')

PS: Not sure if this approach will properly work on production DB where table is heavily updated, but for unit tests it suites well. I use this script to figure out what new seed value i should set for table when doing clean up of that table. Because for never populated table the new seed value must be 1 and 0 otherwise.

于 2021-03-19T09:27:30.210 回答