Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable or parameter to specify restart value for ALTER SEQUENCE

Tags:

c#

sql-server

I have a situation where I need to restart a sequence to a specified value, where this value is specified in either a variable or passed as a parameter programically from a C# program.

The following code is an example of what I hoped would work, but didn't:

DECLARE @current_value AS BigInt = 60000;

ALTER SEQUENCE
    usq_MySequence
RESTART WITH
    @current_value

Something like this does work:

ALTER SEQUENCE
    usq_MySequence
RESTART WITH
    60000

however that's hard coded, and the program I'm interacting with will only pass parameters (Using the SqlCommand in .NET)

Is there anyway to reset a sequence with a variable or parameter?

like image 855
joshhendo Avatar asked Mar 06 '26 04:03

joshhendo


1 Answers

The RESTART WITH value must be a constant. The only way to set it with a variable is to use some dynamic SQL:

DECLARE @current_value AS BigInt = 60000;
DECLARE @s nvarchar(1000);

SET @s = N'
ALTER SEQUENCE
    usq_MySequence
RESTART WITH ' + CAST(@current_value AS nvarchar(10));

EXEC (@s);
like image 123
dean Avatar answered Mar 08 '26 16:03

dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!