1

I am trying to insert variables into SQL Server table dynamically inside a stored procedure but I'm not able to accomplish it because of the syntax. Can someone correct me what am I doing wrong in the below code. Thanks.

Code I have tried:

SET @SQLStmt1 = N'INSERT INTO TestTable (TableName) 
                  VALUES(' + @ResulTableName + N')'
EXEC sp_executesql @SQLStmt1    
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Teja
  • 13,214
  • 36
  • 93
  • 155

2 Answers2

2

You are close, but you should use a parameter for the value:

SET @SQLStmt1 = N'INSERT INTO TestTable( TableName ) 
                              VALUES(@ResulTableName)';

EXEC sp_executesql @SQLStmt1, N'@ResultTableName NVARCHAR(MAX)', 
                   @ResulTableName = @ResulTableName;

If you printed out @SQLStmt1, you would see that the single quotes are not correct.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

you can do it by adding triple quotes ''' this will resolve your problem

SET @SQLStmt1 = N'INSERT INTO TestTable( TableName ) 
                              VALUES(''' + @ResulTableName + ''')'
EXEC sp_executesql @SQLStmt1    

the reason behind that is that triple quote in the dynamic SQL will become a single quote when the code get executed.

asmgx
  • 7,328
  • 15
  • 82
  • 143