Search code examples
sql-serverstored-proceduressql-server-2012sql-server-2014sql-server-2016

Insert variables into a SQL Server table in stored procedure


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    

Solution

  • 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.