CHAR (Transact-SQL)

將 int ASCII 碼轉換成字元。

主題連結圖示Transact-SQL 語法慣例

語法

CHAR ( integer_expression )

引數

  • integer_expression
    這是一個 0 到 255 的整數。如果整數運算式不在這個範圍內,就會傳回 NULL。

傳回類型

char(1)

備註

CHAR 可用來將控制字元插入字元字串。下表顯示一些常用的控制字元。

控制字元

定位字元

char(9)

換行字元

char(10)

歸位字元

char(13)

範例

A. 利用 ASCII 和 CHAR 來列印字串中的 ASCII 值

下列範例會針對 New Moon 字串中的每個字元來列印 ASCII 值和字元。

SET TEXTSIZE 0
-- Create variables for the character string and for the current 
-- position in the string.
DECLARE @position int, @string char(8)
-- Initialize the current position and the string variables.
SET @position = 1
SET @string = 'New Moon'
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)), 
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
   SET @position = @position + 1
   END
GO

以下為結果集:

----------- - 
78          N 
              
----------- - 
101         e 
              
----------- - 
119         w 
              
----------- - 
32            
              
----------- - 
77          M 
              
----------- - 
111         o 
              
----------- - 
111         o 
              
----------- - 
110         n 
              
----------- - 

B. 利用 CHAR 來插入控制字元

下列範例在會傳回文字結果時,利用 CHAR(13),在個別行中列印名稱、電子郵件地址和電話號碼。

USE AdventureWorks;
GO
SELECT FirstName + ' ' + LastName, + CHAR(13)  + EmailAddress + CHAR(13) 
+ Phone
FROM Person.Contact

WHERE ContactID = 1;
GO

以下為結果集:

Gustavo Achong
gustavo0@adventure-works.com
398-555-0132

(1 row(s) affected)