2

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.

2
  • 1
    If you want parameterised dynamic sql, use sp_executesql Commented Jun 15, 2012 at 14:36
  • @Dems - You should post that as an answer Commented Jun 15, 2012 at 14:37

1 Answer 1

3

You can use sp_executesql.

DECLARE
  @IntVariable    int,
  @SQLString      nvarchar(500),
  @ParmDefinition nvarchar(500)
SELECT
  @IntVariable    = 0,
  @SQLString      = N'SELECT UserName FROM TableUser WHERE UserId=@ValueVariable',
  @ParmDefinition = N'@ValueVariable INT'

SP_EXECUTESQL
  @SQLString,
  @ParmDefinition,
  @ValueVariable = @IntVariable;

In essence, it creates a one time stored procedure. The @paramDefinition variable is the parameter signature you'd normally see in a stored procedure, the sql server caches the execution plan, etc, etc.

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.