Test for numeric value?

前端 未结 3 995
别那么骄傲
别那么骄傲 2021-01-20 17:44

The vendor data we load in our staging table is rather dirty. One column in particular captures number data but 40% of the time has garbage characters or random strings.

3条回答
  •  一个人的身影
    2021-01-20 18:15

    WITH x (stringval) AS 
    (
    VALUES ('x2'),(''),('2.2.'),('5-'),('-5-'),('--5'),('.5'),('2 2'),('0.5-'),(' 1 '),('2  '),('3.'),('-4.0')
    )
    SELECT stringval,
    CASE WHEN (
    
    -- Whitespace must not appear in the middle of a number 
    -- (but trailing and/or leading whitespace is permitted)
    RTRIM(LTRIM( stringval )) NOT LIKE '% %'
    
    -- A number cannot start with a decimal point
    AND LTRIM( stringval ) NOT LIKE '.%'
    
    -- A negative decimal number must contain at least one digit between 
    -- the negative sign and the decimal point
    AND LTRIM( stringval ) NOT LIKE '-.%'
    
    -- The negative sign may only appear at the beginning of the number
    AND LOCATE( '-', LTRIM(stringval)) IN ( 0, 1 )
    
    -- A number must contain at least one digit
    AND TRANSLATE( stringval, '0000000000', '123456789') LIKE '%0%'
    
    -- Allow up to one negative sign, followed by up to one decimal point
    AND REPLACE( 
        TRANSLATE( RTRIM(LTRIM(stringval)), '000000000', '123456789'), 
        '0', '') IN ('','-','.','-.')
    )
    THEN 'VALID'
    ELSE 'INVALID'
    END AS stringisvalidnumber
    FROM x
    ;
    

提交回复
热议问题