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    

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How to do this if I have more than one column in the table?
You just add additional parameters for the columns.
-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.

1 Comment

This is a bad practice, particularly unnecessary when using sp_executesql which accepts parameters.

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.