假设有这样一个表
create table temp(
id int ,
name nvarchar(20),
age smallint
)
insert into temp(id,name,age) values(1,'tom',22)
insert into temp(id,name,age) values(2,'bob',23)
insert into temp(id,name,age) values(3,'timi',24)
select * from temp
查询结果如图所示:
普通的排序语句使用order by,并指定asc和desc来区分升序与降序
在某些时候,我们需要按自己指定的方式排序,如2,1,3,我们可以使用charindex实现
select * from #temp order by charindex(cast(id as varchar),'2,1,3')
结果如下
使用这种方法排序,我们也可使用任意一列进行自定义排序,效果相同
//使用name列的顺序进行排序
select * from #temp order by charindex(name,'bob,tom,timi')