I need to create a INSERT statement using parameters. Say I have two variable name @DestinationFields, @InsertValues.
Here @DestinationFields contain the column name like: product,price and @InsertValues contains the values for those two columns, like: Book,100.
Now, How i create a insert command to insert those values where each value need to add a quotation mark .I already tried as
I already tried as
EXEC('INSERT into tbl_test('+@DestinationFields+')values('+@InsertValues+')')
But it’s returning an error.
The name “book” is not permitted in this context. Valid expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
How do I do it? Thanks in advance.
Pretending there is no problem of SQL injection here*, you can quickly fix your code by adding quotation marks around
Book. The value of@ InsertValuesshould beinstead of simply
You need to add quotation marks around each string value; otherwise, strings are interpreted as names, which is not valid.
EDIT : (in response to a comment) If all columns are of
varchartype, you can put quotes around the entire string, and replace all commas with the quote-comma-quote pattern, like this:* You should not put code like this into production, because it can be manipulated to harm your system rather severely. Here is a good illustration of the problem (link).