STRING_ESCAPE (Transact-SQL)STRING_ESCAPE (Transact-SQL)

適用於: 是SQL Server (從 2016 開始) 是Azure SQL Database 否Azure SQL 資料倉儲 否平行處理資料倉儲 APPLIES TO: yesSQL Server (starting with 2016) yesAzure SQL Database noAzure SQL Data Warehouse noParallel Data Warehouse

逸出文字中的特殊字元並傳回逸出之字元的文字。Escapes special characters in texts and returns text with escaped characters. STRING_ESCAPE 是決定性函數。STRING_ESCAPE is a deterministic function.

主題連結圖示 Transact-SQL 語法慣例Topic link icon Transact-SQL Syntax Conventions

語法Syntax

STRING_ESCAPE( text , type )  

引數Arguments

texttext
這是代表應該逸出之物件的 nvarcharexpression 運算式。Is a nvarcharexpression expression representing the object that should be escaped.

typetype
將套用的逸出規則。Escaping rules that will be applied. 目前支援的值是 'json'Currently the value supported is 'json'.

傳回類型Return Types

帶有逸出的特殊與控制字元的 nvarchar(max) 文字。nvarchar(max) text with escaped special and control characters. 目前,STRING_ESCAPE 只能逸出下表中顯示的 JSON 特殊字元。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\b
換頁字元Form feed \f\f
新行New line \n\n
歸位字元Carriage return \r\r
水平 Tab 鍵Horizontal tab \t\t
控制字元Control character 編碼的序列Encoded sequence
CHAR(0)CHAR(0) \u0000\u0000
CHAR(1)CHAR(1) \u0001\u0001
...... ......
CHAR(31)CHAR(31) \u001f\u001f

RemarksRemarks

範例Examples

A.A. 根據 JSON 格式化規則逸出文字Escape text according to the JSON formatting rules

下列查詢會使用 JSON 規則逸出特殊字元並傳回逸出的文字。The following query escapes special characters using JSON rules and returns escaped text.

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

以下為結果集:Here is the result set.

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

B.B. 格式化 JSON 物件Format JSON object

下列查詢會從數字和字串變數建立 JSON 文字,並逸出變數中的任何特殊 JSON 字元。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

CONCAT (Transact-SQL)CONCAT (Transact-SQL)
CONCAT_WS (Transact-SQL)CONCAT_WS (Transact-SQL)
FORMATMESSAGE (Transact-SQL)FORMATMESSAGE (Transact-SQL)
QUOTENAME (Transact-SQL)QUOTENAME (Transact-SQL)
REPLACE (Transact-SQL)REPLACE (Transact-SQL)
REVERSE (Transact-SQL)REVERSE (Transact-SQL)
STRING_AGG (Transact-SQL)STRING_AGG (Transact-SQL)
STUFF (Transact-SQL)STUFF (Transact-SQL)
TRANSLATE (Transact-SQL)TRANSLATE (Transact-SQL)
字串函數 (Transact-SQL)String Functions (Transact-SQL)