we can create udf and use it any where in our command
CREATE
FUNCTION dbo.GetNumeric_Report
(@strAlphaNumeric VARCHAR(4000))
RETURNS INT
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN CONVERT(INT, ISNULL(@strAlphaNumeric,0))
END
Explanation of Above code :
Major use of PATINDEX which takes first argument as patter and return the index of first accurance of match value from expression.
PATINDEX ( '%pattern%' , expression )
And then STUFF delete the accurance match index from expression.
this way only integer value saved.
TEST:select dbo.GetNumeric_Report('ahgf254bshgw3548bjdgahgfkjla');
CREATE
FUNCTION dbo.GetNumeric_Report
(@strAlphaNumeric VARCHAR(4000))
RETURNS INT
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN CONVERT(INT, ISNULL(@strAlphaNumeric,0))
END
Explanation of Above code :
Major use of PATINDEX which takes first argument as patter and return the index of first accurance of match value from expression.
PATINDEX ( '%pattern%' , expression )
And then STUFF delete the accurance match index from expression.
this way only integer value saved.
TEST:select dbo.GetNumeric_Report('ahgf254bshgw3548bjdgahgfkjla');
No comments:
Post a Comment