0

SQL Server 2012

I have values in 'name' column like this

AMOU
VHOR
1A
7W1
11W
12W
and I am using this query to sort them in order
select * from Unit c where expsetid=382 order by CONVERT(INT,substring(name, 0, PATINDEX('%[^0-9]%', name+'z'))) asc When I order by desc I got

12W
11W
7W1
1A
AMOU
VHOR

But I expect them to be in this order when its desc

12W
11W
7W1
1A
VHOR
AMOU
6
  • What database are you using Commented Apr 11, 2014 at 21:40
  • Consult Complex sort of field "string - number - string". Commented Apr 11, 2014 at 21:43
  • I am using SQL Server 2012 Commented Apr 11, 2014 at 21:46
  • Erm what order do they come out in when you order by asc... Commented Apr 11, 2014 at 21:46
  • @DourHighArch the link you gave its not behaving as expected eigther Commented Apr 11, 2014 at 21:49

2 Answers 2

1

Your using 0 as the start index for substring, which should instead be 1.

When you use zero, you actually get an empty string that is being converted to 0 and thus ordering the alpha strings first. When you use 1, you correctly get an conversion to int error.

Sign up to request clarification or add additional context in comments.

1 Comment

I got error when I used '1' "Conversion failed when converting the nvarchar value '11W' to data type int."
0

Thank you all for helping me in finding the solution as I expected. Here is the query which work for my situation.

select * from Unit c 
where expsetid=382
order by Row_Number() over (Order By CONVERT(INT,substring(name, 0, PATINDEX('%[^0-9]%', name+'z')))) desc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.