Transact SQL StripNonNumeric Function
I was looking to scrub some phone fields that allow for some dirty varchar values at the moment, so I needed a tool to strip non-numeric values from the existing data to determine which records had legit phone numbers and which did not. Here is a quick function I wrote to help me with this in case anyone needed something similar. I included both the StripNonNumeric function and a more generic StripPattern function that you can use to basically do the same thing, but strip any pattern you like.
SQL:
-
CREATE CREATE dbo.StripNonNumeric(@value AS VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
-
BEGIN
-
DECLARE @len AS INT
-
DECLARE @pattern AS VARCHAR(5)
-
DECLARE @result AS VARCHAR(MAX)
-
-
SET @len = LEN(@Value)
-
SET @pattern = '[0-9]'
-
SET @result = ''
-
-
WHILE @len> 0
-
BEGIN
-
SET @result = @result + CASE WHEN SUBSTRING(@value,@len,1) LIKE @pattern THEN SUBSTRING(@value,@len,1) ELSE '' END
-
SET @len = @len - 1
-
END
-
RETURN reverse(@result)
-
END
-
-
-
CREATE FUNCTION dbo.StripPattern(@value AS VARCHAR(MAX), @pattern AS VARCHAR(100)) RETURNS VARCHAR(MAX) AS
-
BEGIN
-
DECLARE @len AS INT
-
DECLARE @result AS VARCHAR(MAX)
-
-
SET @len = LEN(@Value)
-
SET @result = ''
-
-
WHILE @len> 0
-
BEGIN
-
SET @result = @result + CASE WHEN SUBSTRING(@value,@len,1) LIKE @pattern THEN SUBSTRING(@value,@len,1) ELSE '' END
-
SET @len = @len - 1
-
END
-
RETURN reverse(@result)
-
END