日期:2014-05-18  浏览次数:20469 次

根据给的ID顺序排序
表名A,ID为自增,Name为Varchar(20),数据如下

ID Name
1 张三
2 李四
3 王五
4 赵六
5 刘七

现在有的Sql语句如下
select * from A where id in (3,2,4,1)
得到结果如下
ID Name
1 张三
2 李四
3 王五
4 赵六

希望得到的结果需要跟in扩后里面的顺序一样,也就是下面这样
ID Name
3 王五
2 李四
4 赵六
1 张三

请问该如何实现?



------解决方案--------------------
SQL code
order by charindex(','+ltrim(id)+',', ',3,2,4,1,')

------解决方案--------------------
declrae @str varchar(100)
set @str=''
select @str=@str+','+ltrim(id) from tbla
select * from tblb
where id in(select id from tbla)
order by charindex(','+ltrim(id),@str)
------解决方案--------------------
select * from A where id in (3,2,4,1) order by charindex( ',' + cast(id as varchar) + ',' , ',3,2,4,1,')