简体   繁体   中英

Reseeding SQL auto increment from current value

I am trying to reseed the auto increment value from the current auto increment value of the table in SQL. I did something like

USE [MyDatabase]
GO

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

I get the following error:

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

Any idea whats going wrong?

In SQL Server, you could save the IDENT_CURRENT value in a variable, like this:

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

To answer your question, your problem is that Current_Identity is an alias to a column, but you did not store it anywhere. This means that the next call you make to DBCC CHECKIDENT cannot reference the column from the previous query.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM