How To Find the ASCII Value of each character in your String – SQL Server

Here’s a simple query that lists the ASCII Value of each character in your string in SQL Server

DECLARE @counter int = 1;
DECLARE @colString varchar(10) = 'AA%#& ';

WHILE @counter <= DATALENGTH(@colString)
BEGIN
SELECT CHAR
(ASCII(SUBSTRING(@colString, @counter, 1))) as [Character],
ASCII(SUBSTRING(@colString, @counter, 1)) as [ASCIIValue]

SET @counter = @counter + 1
END
GO

Here we are using the ASCII function to list the ASCII values of each character

OUTPUT

image

This function can be very useful to find and replace characters like Tabs, LineFeed etc. that may get inserted in a string. Check the last row in the screenshot above. It is the Tab Control Character with ASCII 9.

In case you want to remove the Tab Character, use this query

SET @colString = REPLACE(@colString, CHAR(9), '')

1 comment:

  1. Another method without using a loop is


    DECLARE @counter int
    set @counter = 1;DECLARE @colString varchar(10)
    set @colString= 'AA%#& '
    --;WHILE @counter <= DATALENGTH(@colString) BEGIN SELECT CHAR(ASCII(SUBSTRING(@colString, @counter, 1))) as [Character], ASCII(SUBSTRING(@colString, @counter, 1)) as [ASCIIValue] SET @counter = @counter + 1 END

    select substring(@colString,number,1),ascii(substring(@colString,number,1)) from master..spt_values
    where type='p' and number between 1 and datalength(@colString)

    Madhivanan
    http://beyondrelational.com/blogs/madhivanan

    ReplyDelete