I am receiving an error when attempting to execute the following code that builds a dynamic string to be executed by sp_executesql.
DECLARE @paramDefinition NVARCHAR(500);
DECLARE @ID1 NVARCHAR(20);
DECLARE @StageTable1 NVARCHAR(100);
DECLARE @StageTable2 NVARCHAR(100);
SET @ID1 = '111111111111111111';
SET @StageTable1 = 'TestTable1';
SET @StageTable2 = 'TestTable2';
DECLARE @sqlToExecute NVARCHAR(MAX)
SET @tableCreateSQL = 'SELECT @ID1
INTO @StageTable1
FROM @StageTable2 ';
SET @paramDefinition = '@ID1 NVARCHAR(20),
@StageTable1 NVARCHAR(100),
@StageTable2 NVARCHAR(100)';
EXEC sys.sp_executesql @tableCreateSQL,
@paramDefinition,
@ID1,
@StageTable1,
@StageTable2;
The error I receive states the following:
Incorrect syntax near '@StageTable1'.
Am I incorrectly constructing the SQL string, or is there an issue with the sp_executesql statement?
Best Answer
You can't parameterize column and table names, sorry. You'll need to do this the old way:
Also see: