0

I am using the following Function to remove extra non numeric characters from the column.

ALTER Function [dbo].[fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
    WHILE PATINDEX('%[^0-9]%', @strText) > 0
    BEGIN
        SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
    END
    RETURN @strText
END

but if the value is 99.35, it is making it 9935, but i want it to be 99

Can anyone guide me what i am missing in the regex. and i am not sure if it covering up the spaces too or not

6
  • Just add '.' into the characters that are allowed. Aug 30, 2016 at 21:03
  • u ean like this [^0-9.]
    – user6601036
    Aug 30, 2016 at 21:04
  • if i do like above, it just keeps the decimals as 99.35
    – user6601036
    Aug 30, 2016 at 21:05
  • If it is to extract the value before ., why do you need that logic? Try SELECT LEFT('99.35', 2)
    – techspider
    Aug 30, 2016 at 21:07
  • i had created a function because this function needs to be implemented in numbers of columns, so trying to remove that in the function itself
    – user6601036
    Aug 30, 2016 at 21:09

3 Answers 3

1

If you are not worried there will be multiple decimal points/periods. You can combine a few of the comments and John's answer like so:

ALTER Function [dbo].[fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS INT
AS
BEGIN
    WHILE PATINDEX('%[^0-9.]%', @strText) > 0
    BEGIN
        SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
    END

    RETURN CAST(FLOOR(CAST(@strtext AS NUMERIC)) AS INT)
END
1
  • i need int, i had made a change to return me INT
    – user6601036
    Aug 30, 2016 at 22:41
0

Instead of just replacing the non-numeric character that is going to be a . or a , or some other delimiter for numeric, just get the left from that point.

SET @strText = LEFT(@strText,PATINDEX('%[^0-9]%', @strText) - 1)

EXAMPLES

DECLARE @strText VARCHAR(1000)

SET @strText = '98,255465465'
SET @strText = LEFT(@strText,PATINDEX('%[^0-9]%', @strText) - 1)
SELECT @strText --98

SET @strText = '97.2554,65465'
SET @strText = LEFT(@strText,PATINDEX('%[^0-9]%', @strText) - 1)
SELECT @strText --97

SET @strText = '982/554.65465'
SET @strText = LEFT(@strText,PATINDEX('%[^0-9]%', @strText) - 1)
SELECT @strText --982
0
Declare @String varchar(1000) = '99.35'
Select floor(@String)

Returns 99

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.