1

I am trying to use some dynamic sql. I have generated over 100 parameters, and to speed things up I am trying to use dynamic sql to only insert values into a table that I have to based off of information retrieved from other tables. I have tried many things like adding a cast etc.

Example of what I mean:

DECLARE @var1 NVARCHAR(MAX)

-- Loop through and add various values
SET @var1 = @var1 + @parameterName
-- The parameter name is retrieved from a table that holds this information

the problem is that when I add the parameter name which would be like "@myFirstParameter" into my final expression so something like this:

DECLARE @finalString NVARCHAR(MAX)
SET @finalString = 'INSERT INTO myTableName ([myFirstParameter]) VALUES (@myFirstParameter)'
EXEC(@finalString)

The "@myFirstParameter" does not get replaced by it's value and I get the following error: Must declare the scalar variable "@myFirstParameter".

Does anyone know of a way to go from the string name of a parameter to the actual value? I am trying to avoid hardcoding all the values and any work around I have attempted has failed and given me errors which appear to be much worse than what I have stated above.

1 Answer 1

1

The first way is to add the parameter's value, instead of its name, to the SQL string:

SET @finalString = 'INSERT INTO myTableName ([myFirstParameter]) VALUES (' + 
    @myFirstParameter + ')'

This assumes the parameter has a string value. If not, you have to cast it, like cast(@myFirstParameter as varchar(128)).

The second way is to use sp_executesql instead of exec:

exec sp_executesql 
    N'INSERT INTO myTableName ([myFirstParameter]) VALUES (@myFirstParameter)',
    N'@myFirstParameter varchar(128)',
    @myFirstParameter = @myFirstParameter;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I used a modified version of your second method and it worked like a charm.

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.