0

I am trying to run a sequence from a stored procedure. I am passing the name of the sequence to the stored procedure and the stored procedure will return the sequence value, but the stored procedure is not recognizing the passed sequence name. The error says:

Incorrect syntax near '@SeqName'.

Here's what I have tried:

ALTER PROCEDURE [dbo].[GetSeqNextValue] 
   (@SeqName varchar(50), @NewNum bigint output) 
AS
BEGIN
    SET @NewNum = NEXT VALUE FOR @SeqName
END
2
  • 2
    You cannot pass a sequence name as a parameter in the same way you cannot pass a table name as a parameter to a query. you'll have to use dynamic sql. Commented Jun 29, 2015 at 10:15
  • Please add your use case for passing the sequence name as a variable. Perhaps there is better way, For a thorough discussion on dynamic SQL, see sommarskog.se/dynamic_sql.html. Commented Jun 29, 2015 at 10:20

2 Answers 2

4

You need some dynamic query here:

DECLARE @s NVARCHAR(100) =  'SET @NewNum = NEXT VALUE FOR ' + QUOTENAME(@SeqName)
EXEC sp_executesql @s, N'@NewNum bigint output', @NewNum OUTPUT
Sign up to request clarification or add additional context in comments.

1 Comment

@Ala, hmm, did you went into a huddle? Wasn't this answer 5 min earlier then accepted?
3

you can alter your procedure as .

ALTER PROCEDURE [dbo].[GetSeqNextValue] (@SeqName varchar(50), @NewNum bigint output) 

AS

BEGIN
  Declare  @SQL  Nvarchar(1000)

  Set @SQL  = 'SELECT @NewNum = Next Value for ' + @SeqName 
  Exec sp_executesql @Sql,N'@NewNum bigint output',@NewNum output 


END 

Comments

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.