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)
(ASCII(SUBSTRING(@colString, @counter, 1))) as [Character],
ASCII(SUBSTRING(@colString, @counter, 1)) as [ASCIIValue]

SET @counter = @counter + 1

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



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, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

1 comment:

Unknown 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)