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 AdventureWorks2008R2;
GO
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)