I want to use a variable value in exec where i don't need to create the query itself. I will have a query stored in a field in my database and i just want to execute that using the parameters in that stored procedure. For Example below i declared two variables @ValueVariable is the parameter of stored procedure and what i declared @QueryString is the one i will read from data base and i want to execute that using the value of @ValueVariable.
DECLARE @ValueVariable int=0
@QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId=@ValueVariable'
EXEC(@QueryString)
When i try to execute that i get an error Incorrect syntax near 'SELECT UserName FROM TableUser WHERE UserId=@ValueVariable'
I am aware that i can do it by
@QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId='+@ValueVariable
But i want to use it as stated above. Not making a query in my procedure but using variable value as in string retrieved from DB.
So is there any way i could be able to execute that using the value from the variable in current environment.
sp_executesql