T-SQL Tutorial

STRING_ESCAPE function


The SQL Server STRING_ESCAPE function is a built-in function that helps in escaping special characters within a string. This function was introduced in SQL Server 2016 and is primarily used to prevent potential SQL injection attacks by sanitizing user input before it is used in SQL queries.


Syntax

The syntax of the STRING_ESCAPE function is as follows:

STRING_ESCAPE ( input_string, type )

Here, input_string is the string that needs to be escaped, and type is an optional argument that specifies the type of escaping to be performed. The type parameter can have the following values:

json: Escapes characters that have a special meaning in JSON strings.
xml': Escapes characters that have a special meaning in XML strings.
html': Escapes characters that have a special meaning in HTML strings.
csv': Escapes characters that have a special meaning in CSV strings.
tsql': Escapes characters that have a special meaning in T-SQL strings.
custom': Escapes characters based on a user-defined custom escape list.

If the type parameter is not specified, the default type is 'json'.


Example

The STRING_ESCAPE function replaces the special characters in the input string with their escaped counterparts. For example, if you have a string that contains double quotes (") and you want to escape them for JSON representation, you can use the following query:

DECLARE @input NVARCHAR(100) = 'This is a "quoted" string.';
SELECT STRING_ESCAPE(@input, 'json');


The result of this query will be 'This is a \"quoted\" string.', where the double quotes have been escaped with a backslash.

It is important to note that the STRING_ESCAPE function is not intended to be used as a general-purpose string manipulation function. Its primary purpose is to help in securing dynamic SQL statements by escaping potentially harmful characters. It is always recommended to use parameterized queries or prepared statements to prevent SQL injection attacks instead of relying solely on the STRING_ESCAPE function.

In conclusion, the SQL Server STRING_ESCAPE function is a valuable tool for escaping special characters within strings to prevent SQL injection attacks. By properly sanitizing user input, it enhances the security of SQL queries that involve dynamic string manipulation.