简体   繁体   中英

sql insert values into specific column

I'm trying to insert a nvarchar value into a specific column in a table. The value can possibly have reserved words and single quote chars(as in don't).

what I have is:

set @myString= REPLACE(@myString, '''', '''''');
set @ExecStatement = 'INSERT INTO #TempTable('+@ColumnName+') VALUES('''+@myString+''')';
exec (@ExecStatement)

This works for the vast majority of items but I get this error message:

Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string 'We didn't understand, please resend, or type HE'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'We didn't understand, please resend, or type HE'.

and I'm actually missing the remainder of the text that's supposed to be there. It's supposed to be "We didn't understand, please resend, or type HELP and someone will contact you" .

Any help would be greatly appreciated.

Based on the comment that your output string is:

INSERT INTO #TempTable(Col1) VALUES('We didn''t understand, please resend, or type HELP and someone will contact you.')

You will need to escape the quotes surrounding the string, and quadruple quote the ones that should actually be quotes... Something like

INSERT INTO #TempTable(Col1) VALUES(''We didn''''t understand, please resend, or type HELP and someone will contact you.'')

Using square brackets may help:

set @myString= REPLACE(@myString, '''', '''''');
set @ExecStatement = 'INSERT INTO #TempTable(['+@ColumnName+']) VALUES('''+@myString+''')';
exec (@ExecStatement)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM