Thursday, July 28, 2011

Sort the version number stored in string type

Read some question on stackoverflow on how to get the latest version number, the version number is of string type though. Here's one of my answer (aside from multiplying each digit group ):


with a as
(
 select * from ( values('2.1.4 '), ('2.1.12'), ('2.1.5'), ('2.2.1') ) as b(c)     
),
x as
(
 select c, 
  Ranking = RANK() 
   over(order by 
    convert(int,PARSENAME(c,3)), 
    convert(int,PARSENAME(c,2)), 
    convert(int,PARSENAME(c,1))) 
 from a
)
select * 
from x;

-- PARSENAME usage is inspired by http://www.sql-server-helper.com/tips/sort-ip-address.aspx

Output:
c      Ranking
2.1.4  1
2.1.5  2
2.1.12 3
2.2.1  4


To get the latest version, just sort the query in descending order then get the row with the ranking of 1:

with a as
(
 select * from ( values('2.1.4 '), ('2.1.12'), ('2.1.5'), ('2.2.1') ) as b(c)     
),
x as
(
 select c, 
  Ranking = RANK() 
   over(order by 
    convert(int,PARSENAME(c,3)) desc, 
    convert(int,PARSENAME(c,2)) desc, 
    convert(int,PARSENAME(c,1)) desc) 
 from a
)
select * 
from x 
where Ranking = 1

Output
c     Ranking
2.2.1 1

No comments:

Post a Comment