我有以下查询,根据逗号分隔的列表返回行
Select * from Table where RecordID in (22,15,105,1,65,32)
我希望通过SQL查询结果按照列表中ID的顺序返回。这是否可行?
提前感谢。
我有以下查询,根据逗号分隔的列表返回行
Select * from Table where RecordID in (22,15,105,1,65,32)
我希望通过SQL查询结果按照列表中ID的顺序返回。这是否可行?
提前感谢。
select * from Table
where RecordID in (22,15,105,1,65,32)
order by (
case RecordID
when 22 then 1
when 15 then 2
when 105 then 3
when 1 then 4
when 65 then 5
when 32 then 6 end)
in (22,15,105,1,65,32)
,所以你已经在动态构建查询,因此最好同时构建 order by
。如果没有,你如何为具有动态值列表的查询参数化呢? - Mikael Erikssondeclare @T table (RecordID int,Position int)
insert into @T (RecordID,Position)
select 22,1 union all
select 15,2 union all
select 105,3 union all
select 1,4 union all
select 65,5 union all
select 32,6
select * from Table t inner join @T t2 on t.RecordID = t2.RecordID order by t2.Position
如果您真的想在SQL中进行排序,可以按照以下方式操作:
我会在客户端进行排序,但是如果您确实想在SQL中进行排序,请按照以下步骤操作:
declare @T table (id int identity(1,1), RecordID int)
insert into @T (RecordID)
values (22), (15), (105), (1), (65), (32)
select * from
[table] t
inner join @t s on t.id=s.recordid
where t.id in (22, 15, 105, 1, 65, 32)
order by s.id
(适用于SQL Server 2008)
where t.id in (22, 15, 105, 1, 65, 32)
。 - lanierhall是的。您可以在末尾添加ORDER BY recordedid
子句。
select * from Table where RecordID = 22
union all
select * from table where recordid = 15
等等。
虽然很痛苦,但它起作用了。
UNION
或UNION ALL
没有排序保证 - 引擎可以自由地以其认为最有效的顺序返回结果。这可能会偶然以请求的顺序返回结果,但任何事情(主要版本更改、服务包、热修复、服务器工作负载、时间、月相、衬衫颜色)都可能意味着结果以另一种顺序返回。 - Damien_The_Unbeliever使用ORDER BY
对RecordID
进行排序
Select * from Table where RecordID in (22,15,105,1,65,32) ORDER BY RecordID