如何在 SQL Server 中转义反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6134016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:46:25  来源:igfitidea点击:

How to escape back slash in SQL server

sqlsql-servertsql

提问by Ashish Gupta

DECLARE @Query nvarchar(max)
SET @Query ='DECLARE @Test nvarchar(max)
SELECT @Test = ''\a'\b'\c''
SELECT @Test
PRINT @Query
exec sp_executesql @Query

I am trying to get an output as \a\b\c. The above error is probably because I am not able to escape the \ character.

我试图将输出作为 \a\b\c。上述错误可能是因为我无法转义 \ 字符。

采纳答案by Mitch Wheat

You do not need to escape the backslashes (only the inner single quotes):

您不需要转义反斜杠(只有内部单引号):

DECLARE @Query nvarchar(max)
SET @Query ='DECLARE @Test nvarchar(max)
SELECT @Test = ''\a\b\c''
SELECT @Test'
PRINT @Query
exec sp_executesql @Query

回答by Martin Smith

There is in fact one place where back slashes do need to be escaped (or at least treated specially) in SQL Server.

事实上,在 SQL Server 中有一个地方确实需要对反斜杠进行转义(或至少要进行特殊处理)。

When a backslash immediately precedes a new line in a string literal both the backslash and the new line are removed.

当反斜杠紧接在字符串文字中的新行之前时,反斜杠和新行都将被删除。

PRINT 'Foo\
Bar'

Returns

退货

FooBar

The article hereindicates that this is a feature of the client tools rather than TSQL itself but I don't believe this to be the case as the following code has the same result

这里文章表明这是客户端工具的一个特性,而不是 TSQL 本身,但我不认为是这种情况,因为以下代码具有相同的结果

DECLARE @X VARCHAR(100) = 'PRINT ''Foo\' + CHAR(13) + CHAR(10) + 'Bar'' '
EXEC(@X)

If you actually require a string literal with a backslash followed by carriage returns you can double them up.

如果您确实需要一个带有反斜杠后跟回车符的字符串文字,您可以将它们加倍。

PRINT 'Foo\

Bar'

回答by SenthilPrabhu

If you are using SQL Server 2016 or Later then you can use STRING_ESCAPE() to cast those string with the escape sequence.

如果您使用的是 SQL Server 2016 或更高版本,则可以使用 STRING_ESCAPE() 将这些字符串转换为转义序列。

STRING_ESCAPE( text , type )  

Refer: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-escape-transact-sql?view=sql-server-ver15

参考:https: //docs.microsoft.com/en-us/sql/t-sql/functions/string-escape-transact-sql?view=sql-server-ver15

回答by Marquinho Peli

If you want to test try this code:

如果你想测试试试这个代码:

select '\a\b\c'

选择'\a\b\c'

There is no necessity to escape the backslash character. But the issue of backslash plus newline character is a problem and Sql Server engine simply cut it out.

没有必要转义反斜杠字符。但是反斜杠加换行符的问题是个问题,Sql Server 引擎干脆把它剪掉了。

If you need to put a single quotation mark on the string, then you need to double the quotation mark character:

如果需要在字符串上加上单引号,则需要将引号字符加倍:

select 'test: ''in quotes'' - ok'

选择'测试:''在引号中'' - 好的'

Hope I'd helped in some way.

希望我在某种程度上有所帮助。