2

I am trying to store next value for the sequence into a variable and the statement is called in a dynamic sql as below.

DECLARE @Sequence VARCHAR(100) = 'IMEIIDLookUP'
DECLARE @NextVal INT
DECLARE @SQL NVARCHAR(4000)

SELECT @SQL = 'SELECT (NEXT VALUE FOR [dbo].' + QUOTENAME(@Sequence) + ')'

SELECT  @NextVal = EXEC (@SQL)

SELECT @NextVal

The above query fails with error

Incorrect syntax near the keyword 'EXEC'.

What would be the correct syntax here? Having said that, I cannot avoid using dynamic sql.

2
  • read about sp_execute. It allows passing parameters back and forth Commented Aug 27, 2014 at 0:22
  • nope, it threw the same error. Commented Aug 27, 2014 at 0:37

1 Answer 1

5

Use sp_executesql:

DECLARE @Sequence VARCHAR(100) = 'IMEIIDLookUP';
DECLARE @NextVal INT;
DECLARE @SQL NVARCHAR(4000);

SELECT @SQL = 'SELECT @NextVal = (NEXT VALUE FOR [dbo].' + QUOTENAME(@Sequence) + ')';

exec sp_executesql @SQL, N'@NextVal int output', @NextVal = @NextVal output;

SELECT @NextVal;
Sign up to request clarification or add additional context in comments.

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.