CHAR (Transact-SQL)

將 int ASCII 碼轉換成字元。

適用於:SQL Server (SQL Server 2008 透過目前版本)、Windows Azure SQL 資料庫 (初始版本,透過目前版本)。

主題連結圖示 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) 於個別行中列印員工的名稱和電子郵件地址。 這個範例會使用 AdventureWorks2012 資料庫。

SELECT p.FirstName + ' ' + p.LastName, + CHAR(13)  + pe.EmailAddress 
FROM Person.Person p JOIN Person.EmailAddress pe
ON p.BusinessEntityID = pe.BusinessEntityID
AND p.BusinessEntityID = 1;
GO

以下為結果集:

Ken Sanchez

ken0@adventure-works.com

(1 row(s) affected)

請參閱

參考

+ (字串串連) (Transact-SQL)

字串函數 (Transact-SQL)