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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


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

 
  Feedback:

comments

1 Response to "How To Find the ASCII Value of each character in your String – SQL Server"
  1. Madhivanan said...
    February 3, 2010 at 7:19 AM

    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

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions