In SQL Server, the T-SQL STRING_ESCAPE()
function escapes special characters in texts and returns the text with escaped characters.
You provide the text and the escape type as arguments when calling the function.
Syntax
The syntax goes like this:
STRING_ESCAPE( text , type )
Where text is the text that contains any characters to be escaped, and type determines the escaping rules to apply.
Currently, the only value supported for the type argument is 'json'
.
Example 1 – Basic Usage
Here’s an example of how it works:
SELECT STRING_ESCAPE('\', 'json') AS Result;
Result:
+----------+ | Result | |----------| | \\ | +----------+
Here’s an example where a forward slash is escaped:
SELECT STRING_ESCAPE('/', 'json') AS Result;
Result:
+----------+ | Result | |----------| | \/ | +----------+
And here’s an example with a bit more text:
SELECT STRING_ESCAPE('Free beer/wine with every lambo!', 'json') AS Result;
Result:
+-----------------------------------+ | Result | |-----------------------------------| | Free beer\/wine with every lambo! | +-----------------------------------+
Example 2 – Invalid Type
At the time of writing, the only value supported for the type parameter is 'json'
. Here’s what happens if we supply an unsupported value:
SELECT STRING_ESCAPE('\', 'oops') AS Result;
Result:
An invalid value was specified for argument 2.
Escapable Characters
At the time of writing, the STRING_ESCAPE()
function can only escape the JSON special characters listed in the following table:
Special character | Encoded sequence |
---|---|
Quotation mark (") | \" |
Reverse solidus (\) | \| |
Solidus (/) | \/ |
Backspace | \b |
Form feed | \f |
New line | \n |
Carriage return | \r |
Horizontal tab | \t |
Control character | Encoded sequence |
---|---|
CHAR(0) | \u0000 |
CHAR(1) | \u0001 |
… | … |
CHAR(31) | \u001f |