1

我正在尝试从 SQL 中表的当前自动增量值重新设置自动增量值。我做了类似的事情

USE [MyDatabase]
GO

SELECT IDENT_CURRENT('MyTable') AS Current_Identity
DBCC CHECKIDENT (MyTable, reseed, Current_Identity)

我收到以下错误:

(1 row(s) affected)
Msg 2560, Level 16, State 9, Line 3
Parameter 3 is incorrect for this DBCC statement.

知道出了什么问题吗?

4

2 回答 2

3

在 SQL Server 中,您可以将IDENT_CURRENT值保存在变量中,如下所示:

DECLARE @currentIdentity INT;
SELECT @currentIdentity = IDENT_CURRENT('MyTable');
DBCC CHECKIDENT (MyTable, reseed, @currentIdentity);

要回答您的问题,您的问题是 Current_Identity 是列的别名,但您没有将其存储在任何地方。这意味着您进行的下一次调用DBCC CHECKIDENT无法引用上一个查询中的列。

于 2012-09-06T19:37:56.507 回答
0

If you run the following code on a table that never had a record in it, you will the following error :

Parameter 3 is incorrect for this DBCC statement

DECLARE @max_id INT
SELECT @max_id = MAX(ID)+1 FROM testt; 
DBCC CHECKIDENT('Tablename',RESEED,@max_id);

The reason is that @max_id is NULL in this case and you can't pass it.

Here is what I would do. I would check the value returned to make sure it's not NULL. Hope this helps

DECLARE @max_id INT, @var int
SELECT @max_id = MAX(ID)+1 FROM TABLENAME; 
IF @max_id IS NULL 
BEGIN
SELECT@var = 1 
END
ELSE
BEGIN 
SELECT @var = @max_id
END
DBCC CHECKIDENT('TABLENAME,RESEED,@var);
于 2016-07-18T15:13:45.733 回答