ssmike12
ssmike12

Reputation:

How to sort by number in SQL Server?

I have a table with a column stored as string, but it is really a number like this:

17 - Doe
2 - Mike
3 - James

I need to sort them and create a output like this:

2 - Mike
3 - James
17 - Doe

How to write the SQL? Thanks in advance!

Upvotes: 2

Views: 1248

Answers (3)

Sparky
Sparky

Reputation: 763

Forgive me If I've missed out a point, but I feel this is pretty simple and straightforward. Below is the query i used to get your desired result. It will work for any number preceding a name..

select col from *table_name* order by convert(int,substring(id,0,charindex('-',id)));

Kindly point out someone if I've missed something...

Upvotes: 0

KM.
KM.

Reputation: 103597

try this:

DECLARE @Yourtable table (data varchar(50))
insert into @Yourtable values ('17 - Doe')
insert into @Yourtable values ('2 - Mike')
insert into @Yourtable values ('3 - James')

SELECT * FROM @Yourtable order by CONVERT(int,left(data, charindex('-', data)-1))

You shouldn't store your data this way, add a new int column to this table and run this to fix your table:

DECLARE @Yourtable table (data varchar(50), newINT int)
insert into @Yourtable values ('17 - Doe',null)
insert into @Yourtable values ('2 - Mike',null)
insert into @Yourtable values ('3 - James',null)

UPDATE @Yourtable
    SET newINT=CONVERT(int,left(data, charindex('-', data)-1))
        ,data=RIGHT(data, LEN(data)-charindex('-', data)-1)

you can add an index to the new int column if you need to join or select by it. Now you can do a regular ORDER BY on it.

Upvotes: 8

u07ch
u07ch

Reputation: 13702

Two big assumptions - if the format is always as described then you can pull out the integer in your order by. Dont have sql server to test but something like this

order by cast(left(yourcol, charindex('-', yourcol) as integer))

Upvotes: 2

Related Questions