split alpha and numeric using sql

前端 未结 4 573
夕颜
夕颜 2020-12-09 13:31

I have a table and it has a 3 columns. The first column is the data that contains value(numeric) and unit(percentage and etc..), the second col

4条回答
  •  天命终不由人
    2020-12-09 14:06

    If the numeric part is always at the beginning, then you can use this:

    PATINDEX('%[0-9][^0-9]%', ConcUnit)
    

    to get the index of the last digit.

    Thus, this:

    DECLARE @str VARCHAR(MAX) = '4000 ug/ML' 
    
    SELECT LEFT(@str, PATINDEX('%[0-9][^0-9]%', @str )) AS Number,
           LTRIM(RIGHT(@str, LEN(@str) - PATINDEX('%[0-9][^0-9]%', @str ))) As Unit
    

    gives you:

    Number  Unit
    -------------
    4000    ug/ML
    

    EDIT:

    If numeric data include double values as well, then you can use this:

    SELECT LEN(@str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(@str))
    

    to get the index of the last digit.

    Thus, this:

    SELECT LEFT(@str, LEN(@str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(@str)))
    

    gives you the numeric part.

    And this:

    SELECT LEFT(@str, LEN(@str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(@str))) AS Numeric,
           CASE 
              WHEN CHARINDEX ('%', @str) <> 0 THEN LTRIM(RIGHT(@str, LEN(@str) - CHARINDEX ('%', @str)))
              ELSE LTRIM(RIGHT(@str, PATINDEX ('%[^0-9][0-9]%', REVERSE(@str))))
           END AS Unit
    

    gives you both numberic and unit part.

    Here are some tests that I made with the data you have posted:

    Input:

    DECLARE @str VARCHAR(MAX) = '50 000ug/ML'
    

    Output:

    Numeric Unit
    ------------
    50 000  ug/ML
    

    Input:

    DECLARE @str VARCHAR(MAX) = '99.5%'
    

    Output:

    Numeric Unit
    ------------
    99.5    
    

    Input:

    DECLARE @str VARCHAR(MAX) = '4000 . 35 % ug/ML'
    

    Output:

    Numeric     Unit
    ------------------
    4000 . 35   ug/ML
    

提交回复
热议问题