0

What I'm trying to do is create an SQL function where it checks if a number has any non-numeric characters and if it does remove them. But if the number has a +1234, leave it. So some number have 1234 and some have have +1234. I dont want to add + to all the numbers.

Here is my SQL function below:

CREATE FUNCTION[dbo].[fn_NonNumericCharacters] ( @strText varchar(1000) )
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^+0-9]%', @strText) > 0
BEGIN
    SET @strText = STUFF(@strText, PATINDEX('%[^+0-9]%', @strText), 1,    '')
END
RETURN @strText
END

What I'm trying to do with this function is make it look for these characters ()-,.SPACE .

What do you think?

3
  • 1
    Does it do the job you want it to do? If so, Code Review might be a better site to ask on. Commented Jul 31, 2015 at 13:07
  • Do you only want to replace these characters: ()-,.SPACE? Performance-wise, a nested replace should be faster. Commented Jul 31, 2015 at 13:07
  • Im not sure if it will work yet, i was just wondering id this line 'SET @strText = STUFF(@strText, PATINDEX('%[^+0-9]%', @strText), 1, '')' , while make all number +1234 ? Commented Jul 31, 2015 at 13:11

1 Answer 1

1

Store the first char if its a +, replace +, re-append, return:

CREATE FUNCTION[dbo].[fn_NonNumericCharacters] ( @strText varchar(1000) )
RETURNS VARCHAR(1000)
AS
BEGIN
  DECLARE @prefix VARCHAR(1) = CASE WHEN @strText LIKE '+%' THEN '+' ELSE '' END

  WHILE PATINDEX('%[^0-9]%', @strText) > 0
      SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1,    '')

  RETURN @prefix + @strText
END
Sign up to request clarification or add additional context in comments.

3 Comments

CASE WHEN LEFT(@strText,1) = '+' may be a bit faster.
Thanks so, that looks for '+', then replaces it?, but i dont want to replace it.
Yes, but then it restores the leading + if the input began with + so '+123+4Z56' => '+123456'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.