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

文本中包含了一个引用。

我怎么逃脱呢?

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

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


当前回答

我也遇到了同样的问题,但我的问题不是基于SQL代码本身中的静态数据,而是基于数据中的值。

这段代码列出了我的数据库中所有的列名和数据类型:

SELECT DISTINCT QUOTENAME(COLUMN_NAME),DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS

但是有些列名实际上在列名中嵌入了单引号!,例如……

[MyTable].[LEOS'DATACOLUMN]

为了处理这些,我必须使用REPLACE函数以及建议的QUOTED_IDENTIFIER设置。否则,在动态SQL中使用该列时会出现语法错误。

SET QUOTED_IDENTIFIER OFF;
    SET @sql = 'SELECT DISTINCT ''' + @TableName + ''',''' + REPLACE(@ColumnName,"'","''") + ...etc
SET QUOTED_IDENTIFIER ON;

其他回答

如何:

insert into my_table values('hi, my name' + char(39) + 's tim.')

双引号选项帮助我

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

我们中的许多人都知道,转义单引号的流行方法是像下面这样轻松地将它们重复。

PRINT 'It''s me, Arul.';

我们将研究其他一些转义单引号的替代方法。

1. UNICODE字符

39是单引号的UNICODE字符。我们可以像下面这样使用它。

PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';

2. QUOTED_IDENTIFIER

另一个简单且最佳的替代解决方案是使用QUOTED_IDENTIFIER。 当QUOTED_IDENTIFIER设置为OFF时,字符串可以用双引号括起来。 在这个场景中,我们不需要转义单引号。 所以,这种方法在使用很多带单引号的字符串值时非常有用。 当使用这么多行INSERT/UPDATE脚本(其中列值有单引号)时,这将非常有帮助。

SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;

结论

上述方法适用于AZURE和On Premises。

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.

双倍的引用本应有效,但奇怪的是它没有对你起作用;但是,另一种方法是在字符串周围使用双引号字符,而不是单引号字符。也就是说,

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