开发者

Can double quotes be used to delimit a string?

I was surprised to encounter a SQL 2008 T-SQL proc that used a double quote as a string delimiter. For example:

DECLARE @SqlStmt AS VarChar(5000)
SE开发者_如何学运维T @SqlStmt = "ok"
PRINT @SqlStmt

I didn't think it was allowed. I thought only apostrophes could be used.

Thinking that T-SQL is flexible like Javascript to allow either as delimiters in case you wanted to mix the two in a single statement, I tried to do the same in one of my stored procs because I wanted to construct dynamic SQL that included ticks. I was surprised that the script wouldn't compile, I was getting an "INVALID COLUMN [X]" error where X was the contents of my quoted string.

So, I stripped it down to it simplest components until I got the exact SQL you see above, which compiles, runs, and prints "OK".

Now the real surprising part:

I placed the T-SQL script above on my clipboard, executed Control + N to open a new query window using the same connection and pasted the above script into the new query window and was shocked to see that I was getting the following error in the new window:

Msg 207, Level 16, State 1, Line 3
Invalid column name 'ok'.

Explanation Update:

Apparently I had removed the SET QUOTED_IDENTIFIER from the original script, but I had already executed it in the original query window, but the option was still in effect. When I created a new query Window, the option was reset to off by default.

Thanks for the answers.


If QUOTED_IDENTIFIER is OFF then they can be used to delimit a string. Otherwise items in double quotes will be interpreted as object names.

Always use single quotes to delimit strings and square brackets for those object names that require delimiting so your code doesn't break when run under the "wrong" setting.


Like already Martin Said, you could use like this.

SET QUOTED_IDENTIFIER OFF
BEGIN
DECLARE @SqlStmt AS VarChar(5000)
SET @SqlStmt = "ok"
PRINT @SqlStmt
END
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜