Select max int from varchar column

前端 未结 9 1273
离开以前
离开以前 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:40

    Why not

    SELECT MAX(CAST(Value AS Int)) FROM #bla 
    WHERE ISNUMERIC(Value)=1 
        AND Value LIKE '%[0-9]%' 
    

    then you're only dealing with numeric strings. In this case you may not need ISNUMERIC()

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

    These answers are only half right. They succeed in isolating numeric values, but don't realize that when the underlying field is a number the Max function evaluates as characters (regardless of casting), reading left to right, so that 789 > 1000 because 7 > 1. A way around this might be to forget about casting and left pad the numbers with zeros to a common length, when Max in character mode should work.

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

    Look into casting the column to an int, then selecting the MAX(). I don't know what it will do to columns that contain letters, but it's worth exploring.

    http://doc.ddart.net/mssql/sql70/ca-co_1.htm

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

    You should check this solution out for values like '+' and '-' as I think the IsNumeric function may return 1 for these values

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

    You might try

    Select MAX(BoxNumber) from {table} where IsNumeric(BoxNumber) = 1
    
    0 讨论(0)
  • 2021-02-19 04:54

    The selected answer worked for me until I added this value to the temp table along with the others in the sample:

    insert #bla values('1234')
    

    I expected my max() result to now be 1234, but it remained at 789. Perhaps this is due to some collation setting, but I was able to reproduce on multiple databases. I found this query below worked for me, but I'd certainly be interested to hear if there is a more efficient way of doing this. Also, I did not want to include any decimal values, so I excluded anything with a period as well.

    SELECT MAX(CAST(Value AS Int)) FROM #bla 
    WHERE ISNUMERIC(Value)=1 
        AND Value NOT LIKE '%[a-z]%' 
        AND Value NOT LIKE '%.%'
    
    0 讨论(0)
提交回复
热议问题