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.