This will definitely get the last 6 digits from the argument you pass.
One remark. In SQL Server 2005, the \ character (backslash) does not return 1 ISNUMERIC. But this happens in SQL Server 2008. This function should work in both versions of SQL Server, since we simply exclude this character in the seventh of my test argument above.
PRINTING THE RIGHT (dbo.fnNumericDigits ('5-555-555551-2345-6-'), 6)
Scalar Function:
ALTER FUNCTION [dbo].[fnNumericDigits] ( @startString NVARCHAR(255) ) RETURNS NVARCHAR(255) AS BEGIN DECLARE @returnString NVARCHAR(255) DECLARE @length INT, @currentDigit INT, @currentCharacter NVARCHAR(1) SELECT @length = LEN(@startString), @currentDigit = 1, @returnString = '' WHILE @currentDigit <= @length BEGIN SELECT @currentCharacter = SUBSTRING(@startString, @currentDigit, @currentDigit) IF ISNUMERIC(@currentCharacter) = 1 AND @currentCharacter != '$' AND @currentCharacter != '+' AND @currentCharacter != ',' AND @currentCharacter != '-' AND @currentCharacter != '.' AND @currentCharacter != '\' BEGIN SELECT @returnString = @returnString + @currentCharacter END SELECT @currentDigit = @currentDigit + 1 END RETURN @returnString END
source share