Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape back slash in SQL server

Tags:

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.

like image 795
Ashish Gupta Avatar asked May 26 '11 05:05

Ashish Gupta


People also ask

How do I escape a special character in SQL?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

How do you backslash in SQL query?

\ is a special character known as an escape character that indicates that the character directly following it should be interpreted literally (useful for single quotes, wildcard characters, etc.). will select records with txt1 values of 'xa1', 'xa taco', 'ya anything really', etc.

How do I escape a string in SQL Server?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.


2 Answers

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 
like image 103
Mitch Wheat Avatar answered Sep 21 '22 15:09

Mitch Wheat


There is in fact one place where back slashes do need to be escaped (or at least treated specially) in 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 here indicates 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

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' 
like image 35
Martin Smith Avatar answered Sep 18 '22 15:09

Martin Smith