在有些情况下我们需要按指定顺序输出数据,比如选择了ID
in(3,1,2,5,4)我们希望按这个3,1,2,5,4的顺序输出,这样只使用order by ID是无法实现的,但是我们可以使用order by charindex(','+convert(varchar,ID)+',',',3,1,2,5,4,')的方法来实现这个目的。举例如下:
Create Table info(
ID int identity(1,1) not null,
title varchar(100) not null
)
insert into info(title) values('aa')
insert into info(title) values ('bb')
insert into info(title)values('cc')
insert into info(title) values('dd')
insert into info(title)values('ee')
select id,title
from info
where id in ('3','1','2','5','4')
order by charindex(','+convert(varchar,ID)+',',',3,1,2,5,4,')
本文介绍了一种在SQL中实现自定义排序顺序的方法,通过使用charindex和convert函数结合特定ID列表来达到按预设顺序输出数据的目的。

1060

被折叠的 条评论
为什么被折叠?



