我试图将一些文本数据插入到SQL Server 9中的表中。

文本中包含了一个引用。

我怎么逃脱呢?

我尝试使用两个单引号,但它给我带来了一些错误。

如。插入my_table值('hi, my name' s tim.');


当前回答

通过将单引号加倍来转义,就像您在示例中展示的那样。下面的SQL说明了这个功能。我在SQL Server 2008上进行了测试:

DECLARE @my_table TABLE (
    [value] VARCHAR(200)
)

INSERT INTO @my_table VALUES ('hi, my name''s tim.')

SELECT * FROM @my_table

结果

value
==================
hi, my name's tim.

其他回答

Also another thing to be careful of is whether or not it is really stored as a classic ASCII ' (ASCII 27) or Unicode 2019 (which looks similar, but not the same). This isn't a big deal on inserts, but it can mean the world on selects and updates. If it's the unicode value then escaping the ' in a WHERE clause (e.g where blah = 'Workers''s Comp') will return like the value you are searching for isn't there if the ' in "Worker's Comp" is actually the unicode value.If your client application supports free-key, as well as copy and paste based input, it could be Unicode in some rows, and ASCII in others! A simple way to confirm this is by doing some kind of open ended query that will bring back the value you are searching for, and then copy and paste that into notepad++ or some other unicode supporting editor. The differing appearance between the ascii value and the unicode one should be obvious to the eyes, but if you lean towards the anal, it will show up as 27 (ascii) or 92 (unicode) in a hex editor.

这应该可以

DECLARE @singleQuote CHAR 
SET @singleQuote =  CHAR(39)

insert into my_table values('hi, my name'+ @singleQuote +'s tim.')

下面的语法将只转义一个引号:

SELECT ''''

结果将是一个单引号。对于创建动态SQL:)可能非常有帮助。

有两种方法可以解决这个问题:


对于',你可以简单地在字符串中加倍它,例如。 选择'I' m happy '——将得到:I'm happy


对于任何你不确定的字符:在sql server中,你可以通过选择unicode(':')来获得任何字符的unicode(你保留这个数字)

在这种情况下你还可以选择I +nchar(39)+ m happy

双引号选项帮助我

SET QUOTED_IDENTIFIER OFF;
insert into my_table values("hi, my name's tim.");
SET QUOTED_IDENTIFIER ON;