简体   繁体   English

从当前值重新设置SQL自动增量

[英]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. 我试图从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: 在SQL Server中,您可以将IDENT_CURRENT值保存在变量中,如下所示:

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. 要回答您的问题,您的问题是Current_Identity是列的别名,但您没有将其存储在任何位置。 This means that the next call you make to DBCC CHECKIDENT cannot reference the column from the previous query. 这意味着您对DBCC CHECKIDENT的下一个调用无法引用上一个查询中的列。

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 此DBCC语句的参数3不正确

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. 原因是@max_id在这种情况下为NULL,您无法传递它。

Here is what I would do. 这就是我要做的。 I would check the value returned to make sure it's not NULL. 我会检查返回的值,以确保它不是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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