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.