Sunday 4 January 2015

T-SQL code to parse Numbers from a String


DECLARE @Str VARCHAR(100) = 'My 1st code is D$34A and 2nd code is E#078!!!'
DECLARE @Position SMALLINT = 0
SET @Position = PATINDEX('%[^0-9]%', @Str) --Find first character

WHILE (@Position > 0)
BEGIN
    -- Replace alphabet with empty string.
    SET @Str = STUFF(@Str, @Position, 1, '')
   
    -- Find next alphabet
    SET @Position = PATINDEX('%[^0-9]%', @Str)
END
SELECT @Str Result



Result
-------------------------------------
1342078

No comments:

Post a Comment