Skip to content

Latest commit

 

History

History
105 lines (80 loc) · 3.45 KB

string-escape-transact-sql.md

File metadata and controls

105 lines (80 loc) · 3.45 KB
title description author ms.author ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs monikerRange
STRING_ESCAPE (Transact-SQL)
STRING_ESCAPE (Transact-SQL)
MikeRayMSFT
mikeray
02/25/2016
sql
t-sql
reference
STRING_ESCAPE
STRING_ESCAPE_TSQL
STRING_ESCAPE function
TSQL
= azuresqldb-current || >= sql-server-2016 || >= sql-server-linux-2017

STRING_ESCAPE (Transact-SQL)

[!INCLUDE sqlserver2016-asdb-asdbmi]

Escapes special characters in texts and returns text with escaped characters. STRING_ESCAPE is a deterministic function, introduced in SQL Server 2016.

:::image type="icon" source="../../includes/media/topic-link-icon.svg" border="false"::: Transact-SQL syntax conventions

Syntax

STRING_ESCAPE( text , type )  

Arguments

text
Is a nvarchar expression representing the object that should be escaped.

type
Escaping rules that will be applied. Currently the value supported is 'json'.

Return Types

nvarchar(max) text with escaped special and control characters. Currently STRING_ESCAPE can only escape JSON special characters shown in the following tables.

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

Remarks

Examples

A. Escape text according to the JSON formatting rules

The following query escapes special characters using JSON rules and returns escaped text.

SELECT STRING_ESCAPE('\   /  
\\    "     ', 'json') AS escapedText;  

[!INCLUDEssResult]

escapedText  
-------------------------------------------------------------  
\\\t\/\n\\\\\t\"\t

B. Format JSON object

The following query creates JSON text from number and string variables, and escapes any special JSON character in variables.

SET @json = FORMATMESSAGE('{ "id": %d,"name": "%s", "surname": "%s" }',
    17, STRING_ESCAPE(@name,'json'), STRING_ESCAPE(@surname,'json') );  

See Also