Convert string to ASCII
February 9, 2010
Leave a comment
A simple SQL function I created to convert a string to ASCII values.
-- =============================================
-- Author: Amit Singh
-- Description: Convert string to ASCII values
-- Usage: SELECT dbo.ToASCII('Amit')
-- =============================================
CREATE FUNCTION ToASCII
(@string AS VARCHAR(2000))
RETURNS VARCHAR(5000)
AS
BEGIN
SET @string = UPPER(@string)
DECLARE @Output VARCHAR(5000)
DECLARE @position INT
SET @position = 1
WHILE @position <= DATALENGTH(@string)
BEGIN
SELECT @Output = COALESCE(@Output, '')
+ CAST(ASCII(SUBSTRING(@string, @position, 1)) AS VARCHAR(3))
SET @position = @position + 1
END
RETURN @Output
END
-- =============================================
GO
This function is build as per my requirements but you can modify it to get desired results.
For example you can replace
COALESCE(@Output, '')
with
COALESCE(@Output + ',', '')
to get a delimited output.
Categories: Programming