T-SQL Tutorial

How to escape character


In SQL Server, you can use the STRING_ESCAPE function to escape special characters in a string. The STRING_ESCAPE function can be used to escape characters such as quotes, tabs, line breaks, and other special characters that may cause issues when included in a string value.

To escape characters using the STRING_ESCAPE function in SQL Server, follow these steps:

1. Start by identifying the string value that you want to escape characters in. This could be a column in a table or a literal value.

2. Call the STRING_ESCAPE function, passing in the string value as the first argument and the type of escaping to use as the second argument. The types of escaping available are 'json', 'xml', 'csv', or 'tsv'.

Syntax

STRING_ESCAPE( text , type )


Example

For example, to escape a string value using JSON escaping, you can use the following code:

SELECT STRING_ESCAPE('This is a "string" value', 'json');

This will escape the double quotes in the string value by adding a backslash before each one, resulting in the following output:

This is a \"string\" value

3. Use the escaped string value as needed in your SQL statements.

By using the STRING_ESCAPE function in SQL Server, you can ensure that your string values are properly escaped and do not cause any issues when used in SQL statements.

Note that the STRING_ESCAPE function is only available in SQL Server 2016 and later versions, and the supported formats may vary depending on the version of SQL Server you're using.