12

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?

2
  • The documentation is quite clear - the syntax diagram is full of <constant> and nothing else for specifying the values. Commented May 1, 2014 at 7:34
  • Thanks; deans answer solves the problem given the restrictions. Commented May 1, 2014 at 10:55

2 Answers 2

27

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this:

select setval('seq_name', variable, true);

1 Comment

[S0010][195] Line 4: 'setval' is not a recognized built-in function name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.