The SQL STRING_ESCAPE String Function is used to escape special characters from string expression, and returns a string with escaped characters. In SQL Server, special characters have a special meaning, and if they are present in a string, they should be escaped.
For example, a string (product description) may have quotation marks in a product name. To escape it, we must add a backslash (\) before it. To do so, we use the STRING_ESCAPE() function.
The basic syntax of the SQL STRING_ESCAPE function is
STRING_ESCAPE (String_Expression, type)
The list of arguments available for STRING_ESCAPE is:
- String_Expression: Please specify a valid String Expression.
- type: Currently, this SQL Server function accepts only JSON type. Please refer to the list of SQL String Functions from our SQL Server tutorial page.
SQL STRING_ESCAPE Example
The following String Function query will show you the examples of string escape. Please refer to the SQL STRING_SPLIT and SQL STRING_AGG functions.
SELECT STRING_ESCAPE('" /', 'json') AS Escape1;
SELECT STRING_ESCAPE('\ /', 'json')AS Escape2;
SELECT STRING_ESCAPE('\ "
', 'json') AS Escape3;
SELECT STRING_ESCAPE('\
/', 'json') AS Escape4;
SELECT STRING_ESCAPE('\
/
', 'json') AS Escape5;

Example 2: The following query escapes the special character \ from a string.
SELECT STRING_ESCAPE('Tutorial \Gate\way', 'json')
Tutorial \\Gate\\way
Example 3: Similarly, in the example below, the STRING_ESCAPE() function escapes the horizontal tab (\t) and new line(\n) by adding a backslash before them.
SELECT STRING_ESCAPE('Tutorial \tGateway\n', 'json')
Tutorial \\tGateway\\n
Example 4: If the task is to escape a control character, we can use STRING_ESCAPE().
SELECT STRING_ESCAPE(CHAR(1), 'json')
\u0001
Example 5: If the string has a system folder address or website URL, they include \ or /. To process this string, use STRING_ESCAPE(), which adds an extra backslash.
SELECT STRING_ESCAPE('C:\Users\Suresh\Documents', 'json')
C:\\Users\\Suresh\\Documents