1

I'm using this code to remove non numeric characters from a string:

ALTER FUNCTION [dbo].[StripNonNumerics](@Temp VARCHAR(255))
RETURNS VARCHAR
AS
BEGIN
    DECLARE @KeepValues AS VARCHAR(50);
    SET @KeepValues = '%[^0-9]%';

    WHILE PATINDEX(@KeepValues, @Temp) > 0 
    BEGIN
        SET @Temp = STUFF(@Temp, PATINDEX(@KeepValues, @Temp), 1, ''); 
    END

    RETURN @Temp
 END;

I expect that if I call this function, putting as input a string like this one:

select [dbo].[StripNonNumerics]('vAn34nd2')

I could get this output:

342

Instead, I obtain:

3

I changed input to test this behaviour, and I noticed that it takes only the first non numeric characters sequence. Could you tell me what I'm overlooking?

Thanks

1
  • 3
    Bad habits to kick : declaring VARCHAR without (length) - you should always provide a length for any varchar variables and parameters that you use. Otherwise, they might end up being a default length, which in case of a parameter or return value is 1 CHARACTER ..... Commented Aug 2, 2017 at 11:12

2 Answers 2

4

Just change the return definition to read:

RETURNS varchar(255)

If you omit the length, the the default length is 1

Sign up to request clarification or add additional context in comments.

Comments

2

I am just adding one another way of doing the above..

DECLARE @X VARCHAR(100)='vAn34nd2', @Y VARCHAR(100)=''

SELECT @Y = @Y+ VAL FROM(
SELECT SUBSTRING(@X,number,1) AS VAL 
FROM master.dbo.spt_values 
WHERE type='P' AND number BETWEEN 1 AND LEN(@X)
AND ISNUMERIC(SUBSTRING(@X,number,1))=1
)A

SELECT @Y

Comments

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.