Introduction
The goal of the original tip was to get the numbers from a text. The numbers could be separated by any non-digit character.
When I first looked at the original tip a few things caught my eye:
1. The many times the SUBSTRING
function was called.
2. The need to look ahead in the string to determine if the number was finished.
3. The use of the Split
function to get the result in the return table.
This is my attempt at a more efficient way of retrieving the numbers from the text.
The function
CREATE FUNCTION dbo.GetNumbersFromText( @String VARCHAR(2000) )
RETURNS @Number TABLE( Number INT )
BEGIN
DECLARE @Count INT = 0;
DECLARE @Character VARCHAR(1) = ''
DECLARE @NumberText VARCHAR(2000) = ''
WHILE @Count <= LEN( @String )
BEGIN
SET @Character = SUBSTRING( @String, @Count, 1 )
IF( @Character >= '0' AND @Character <= '9' )
BEGIN
SET @NumberText = @NumberText + @Character
END
ELSE
BEGIN
IF( LEN( @NumberText ) > 0 )
BEGIN
INSERT INTO @Number SELECT @NumberText
SET @NumberText = ''
END
END
SET @Count = @Count + 1
END
IF( LEN( @NumberText ) > 0 )
BEGIN
INSERT INTO @Number SELECT @NumberText
SET @NumberText = ''
END
RETURN
END