The SQL CHAR function is a SQL String Function used to convert the user specified integer value (ASCII code) to a character. This SQL CHAR function is exactly opposite to the ASCII Function
SQL CHAR Function Syntax
The syntax of the SQL Server CHAR Function is as shown below:
SELECT CHAR (int_Expression) FROM [Source]
int_Expression: Please specify the valid integer value or Expression for which you want to find the character. The specified integer value range should be between 0 and 255, and if you exceed the range, then the CHAR function will return NULL as output.
TIP: Please refer ASCII Table to check the SQL Server ASCII codes of each character.
The SQL Server CHAR function can be used to insert the control characters. The below table will show you some of the most frequently used control characters.
Control Character | Value |
---|---|
Tab | CHAR(9) |
Line Feed | CHAR(10) |
Carriage return | CHAR(13) |
Return Type
This function will return CHAR(1)
SQL CHAR Function Example 1
The CHAR Function convert the given integer value to the character. The following query may show you multiple ways to use this CHAR function.
DECLARE @x INT DECLARE @y INT DECLARE @z CHAR(2) -- Initialize the variables. SET @x = 75 SET @y = 105 SET @z = 'T' SELECT CHAR(@x) AS Result1, CHAR(@y) AS Result2, CHAR(ASCII(@Z)) AS Result3; SELECT CHAR(204) AS Result4; SELECT CHAR('71') AS Result5;
OUTPUT
ANALYSIS
Here, we are finding the characters at the integer values 75 and 105.
SELECT CHAR(@x) AS Result1, CHAR(@y) AS Result2, CHAR(ASCII(@Z)) AS Result3;
In the next line, We used the integer value directly inside the Sql Server CHAR function
SELECT CHAR(204) AS Result4;
You can see from the below statement, We specified the string value 71, but SQL is implicitly converting string 71 to integer 71 and returning the character at 71.
SELECT CHAR('71') AS Result5;
CHAR Function Example 2
In this String Function example, We are going to use the CHAR function inside the WHILE LOOP. I suggest you refer the ASCII function, SUBSTRING, and WHILE LOOP articles to know the query execution.
DECLARE @i INT, @int_expression VARCHAR(50); -- Initialize the variables. SET @i = 1; SET @int_expression = '959871737882'; WHILE @i <= LEN(@int_expression) BEGIN SELECT SUBSTRING(@int_expression, @i, 2) AS [ASCII_Value], CHAR(SUBSTRING(@int_expression, @i, 2)) AS [ASCII_Value] SET @i = @i + 2 END;
OUTPUT