musings

February 18, 2008

Sorting alpha and numeric data in the same field

Filed under: SQL statements — aliaspooryorik @ 3:16 pm

The problem I had was the client was entering some room names as numbers and others as a number with a character at the end. When MS SQL server sorts the column it does it by the field data type (in this case nvarchar), which meant you would get this:

108, 109, 11, 110, 111D, 112D

To get a list like this:

11, 108, 109, 110, 111D, 112D

I modified the query using the IsNumeric function in MS SQL Server to this:

Select [room_name],
  Case When IsNumeric(room_name) = 1 Then Cast(room_name as int) Else 9999999 End As room_sort
from [Rooms]
order by room_sort

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.