How do you use the STRING_ESCAPE function to safely escape special characters in a string?
Posted by JackBrn
Last Updated: June 07, 2024
The STRING_ESCAPE function in SQL Server is used to escape special characters in a string, making it safe for use in contexts where those characters might otherwise cause issues, such as JSON strings or XML content. This function is particularly useful for ensuring that strings do not break the expected format when processed by applications or stored in databases.
Syntax:
STRING_ESCAPE ( string_expression , type )
Parameters:
- string_expression: The string to be escaped. - type: Specifies the type of escaping to be used. Common values include: - 'json': Escapes characters in a string for safe JSON output. - 'xml': Escapes characters for safe XML output (available in SQL Server 2022 and later).
Example Usage:
Here’s how to use the STRING_ESCAPE function for JSON escaping:
DECLARE @json NVARCHAR(MAX);
SET @json = '{"name": "John "Doe", "age": 25}';  -- Note the inner quotes

-- Escape the string for JSON
SELECT STRING_ESCAPE(@json, 'json') AS EscapedJson;
In this example, the output will ensure that the inner double quotes in the JSON string are properly escaped so that the resulting string is correctly formatted JSON.
Output:
The escaped JSON output might look something like this:
{"name": "John \"Doe\"", "age": 25}
When Not to Use:
Keep in mind that, while STRING_ESCAPE helps with escaping special characters, it is primarily intended for JSON or XML contexts. If you're dealing with SQL statements directly or other specific contexts, other handling may be required, including proper parameterization to avoid SQL injection.
Note:
- STRING_ESCAPE was introduced in SQL Server 2016 for JSON escaping, and XML escaping support was added in SQL Server 2022. Check your SQL Server version to ensure compatibility.