sql将值插入特定列

时间:2014-04-18 17:33:52

标签: sql sql-server insert sql-server-2008-r2

我正在尝试将nvarchar值插入表格中的特定列。该值可能包含保留字和单引号字符(如同)。

我所拥有的是:

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

这适用于绝大多数项目,但我收到此错误消息:

  

Msg 105,Level 15,State 1,Line 1
  字符串后面的未闭合引号'我们不明白,请重新发送或输入HE'   消息102,级别15,状态1,行1   “我们不理解,请重新发送或输入HE”附近的语法不正确。

我实际上错过了应该存在的文本的其余部分。它应该是"We didn't understand, please resend, or type HELP and someone will contact you"

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

根据您的输出字符串为的注释:

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

你需要转义字符串周围的引号,然后四倍引用实际应该引用的引号......类似

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

答案 1 :(得分:0)

使用方括号可能会有所帮助:

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