Replace numbers with special characters in SQL select query

Mohammed Imtiyaz Jun 15, 2014

Introduction

This SQL user defined function is used to replace integer values with special characters in a query string.

CREATE FUNCTION dbo.udf_replaceNumbersWithSpecialCharacters(@str NVARCHAR(1000))
    RETURNS NVARCHAR(2000)
AS
BEGIN 

DECLARE @i int = 1
WHILE @i <= LEN(@str)
    BEGIN          
        DECLARE @val VARCHAR(1)
        SET @val = SUBSTRING(@str, @i, 1)
        
        IF ASCII(@val) >= '48' and ASCII(@val) <= '57'
            BEGIN
                    DECLARE @newchar VARCHAR(1)
                    SET @newchar =  CASE ASCII(@val)
                
                    WHEN 48 THEN '!'
                    WHEN 49 THEN '@'
                    WHEN 50 THEN '#'
                    WHEN 51 THEN '$'
                    WHEN 52 THEN '%'
                    WHEN 53 THEN '^'
                    WHEN 54 THEN '&'
                    WHEN 55 THEN '('
                    WHEN 56 THEN ')'
                    WHEN 57 THEN '_'
            END
        SET @str = CAST(REPLACE(@str, @val, @newchar) AS VARCHAR(1000))
    END 
    SET  @i+=1
END
RETURN @str
END

SQL Query

SELECT dbo.udf_replaceNumbersWithSpecialCharacters('hello 123 world456') As Output

Output

SQL user defined function to replace integer values with special characters in a string.