SQL Server sequence set current value

倖福魔咒の 提交于 2021-01-21 18:10:32

问题


I am using SQL Server 2012 (v11.0.2100) and I want to create a sequence that starts with a random (dynamic) number but I wasn't able to do this, also I put my effort to find a good solution for this but I haven't found something that will satisfy me.

The case that I tried and failed:

 DECLARE @sth bigint

 SET @sth = 1000

 ALTER SEQUENCE StreamEntrySequence
 RESTART WITH @sth;

Error :

Incorrect syntax near '@sth'

An ugly solution

 declare @sth bigint;
 declare @i bigint;

 SET @sth = 100000    ; 

 while @i<@sth;
 BEGIN
    SET @i= next value for StreamEntrySequence;
 END

Is there other way to set the current value or the start value to a random value? Maybe using server procedures?


回答1:


As has been mentioned, this would require dynamic SQL since alter sequence requires a constant for the restart argument.

You might do something like this, then:

DECLARE @sth bigint;
SET @sth = 1000;
DECLARE @sql nvarchar(max);
SET @sql = N'ALTER SEQUENCE StreamEntrySequence RESTART WITH ' + cast(@sth as nvarchar(20)) + ';';
EXEC SP_EXECUTESQL @sql;



回答2:


Try

ALTER SEQUENCE foo.fee
RESTART

Or:

ALTER SEQUENCE foo.fee
RESTART WITH 1

http://msdn.microsoft.com/en-us/library/ff878572.aspx




回答3:


Just use

SELECT setval('seq',0,false);

It sets the value of the sequence "seq" to 0.



来源:https://stackoverflow.com/questions/27135200/sql-server-sequence-set-current-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!