Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MAX value of numeric values in varchar column

I have a table with a nvarchar column. This column has values for example:

  • 983
  • 294
  • a343
  • a3546f

and so on.

I would like to take MAX of this values, but not as text but like from numerics. So in this example numerics are:

  • 983
  • 294
  • 343
  • 3546

And the MAX value is the last one - 3546. How to do this in TSQL on Microsoft SQL?

like image 418
Tom Smykowski Avatar asked Apr 01 '09 14:04

Tom Smykowski


People also ask

How do I find the maximum value of a numeric column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

Can we use MAX function on VARCHAR?

The MAX() function can be allpied on the varchar columns.

What is the max of VARCHAR Max?

varchar [ ( n | max ) ] Variable-size string data. Use n to define the string size in bytes and can be a value from 1 through 8,000 or use max to indicate a column constraint size up to a maximum storage of 2^31-1 bytes (2 GB).

How do you get the max value of a string in SQL?

You can use CAST() with MAX() for this. Since the string is filled with string and integer, fir example, β€œSTU201”, therefore we need to use CAST().


2 Answers

First install a regular expression function. This article has code you can cut/paste.

Then with RegexReplace (from that article) you can extract digits from a string:

dbo.RegexReplace( '.*?(\d+).*', myField, '$1' )

Then convert this string to a number:

CAST( dbo.RegexReplace( '.*?(\d+).*', myField, '$1' ) AS INT )

Then use this expression inside a MAX() function in a SELECT.

like image 126
Jason Cohen Avatar answered Oct 14 '22 15:10

Jason Cohen


You can try to keep it simple without using Regular Expression alt text

Here is the source

create table #t ( val varchar(100) )
insert #t select 983
insert #t select 294
insert #t select 'a343'
insert #t select 'a3546f';
GO

;with ValueRange as (
    select  val,
        [from] = patindex('%[0-9]%', val), 
        [to] = case patindex('%[a-z]', val) 
            when 0 then len(val) 
            else patindex('%[a-z]', val) - patindex('%[0-9]%', val) 
               end
    from    #t
)
select  substring(val, [from], [to]) as val
from    ValueRange VR
order by cast(substring(val, [from], [to]) as int) desc
like image 24
dance2die Avatar answered Oct 14 '22 15:10

dance2die