September 18, 2009

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), '')


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

1 comment:

Madhivanan said...

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