Select max int from varchar column

前端 未结 9 1275
离开以前
离开以前 2021-02-19 04:07

I am trying to retrieve the largest number from a varchar column that includes both numbers and strings. An example of the data I\'m working with:

BoxNumber

相关标签:
9条回答
  • 2021-02-19 04:57
    SELECT MAX(CAST(value as signed)) FROM yourTable
    WHERE VALUE NOT LIKE '%[a-z]%'
    AND ISNUMERIC(VALUE) = 1
    

    In MySql

    You should use signed instead of int to cast correctly.

    P.s types used to cast may differ in MySql

    For more conversions visit this link

    0 讨论(0)
  • 2021-02-19 04:58

    you need a combination because of the fact that isnumeric returns 1 for the following things

    select isnumeric('+'),isnumeric('5d2') 
    

    your where clause would be like this

    WHERE VALUE NOT LIKE '%[a-z]%'
            AND ISNUMERIC(VALUE) = 1
    
    create table #bla (value varchar(50))
    insert #bla values('123')
    insert #bla values('a5')
    insert #bla values('789')
    insert #bla values('b1')
    
    SELECT MAX(CAST(value AS Int)) FROM #bla
    WHERE VALUE NOT LIKE '%[a-z]%'
        AND ISNUMERIC(VALUE) = 1
    

    I wrote about this here ISNUMERIC Trouble

    0 讨论(0)
  • 2021-02-19 05:06

    Well, in the intervening 11 years since this question was asked, SQL Server gained the try_cast function, which returns null rather than throwing an error if the conversion doesn't succeed. So in current versions of SQL Server, a valid answer is

    select max(try_cast(BoxNumber as int)) from theTable
    
    0 讨论(0)
提交回复
热议问题