欢迎光临
我们一直在努力

如何按指定的顺序获取数据-数据库专栏,SQL Server

建站超值云服务器,限时71元/月

原贴地址:http://community.csdn.net/expert/topic/3693/3693091.xml?temp=.6086542

测试table
create table table1 (id int,name char)
insert into table1
select 1,q
union all select 2,r
union all select 3,3
union all select 4,5

要求按指定的id顺序(比如2,1,4,3)排列获取table1的数据

方法1:使用union all,但是有256条数据的限制
select id,name from table1 where id=2
union all
select id,name from table1 where id=1
union all
select id,name from table1 where id=4
union all
select id,name from table1 where id=3

方法2:在order by中使用case when
select id ,name from t where id in (2,1,4,3)
order by (case id
                      when 2 then a
                      when 1 then b
                      when 4 then c
                      when 3 then d end)

*以上两种方法适合在数据量非常小的情况下使用

方法3:使用游标和临时表
先建一个辅助表,里面你需要的顺序插入,比如2,1,4,3
create table t1(id int)
insert into t1
select 2
union all select 1
union all select 4
union all select 3

declare @id int                              –定义游标
declare c_test cursor for
select id from t1                       

select * into #tmp from table1 where 1=2     –构造临时表的结构

open c_test

fetch next from c_test
into @id
while @@fetch_status = 0
begin
–按t1中的id顺序插数据到临时表
insert into #tmp select id,name from table1 where id=@id  
fetch next from c_test  into @id
end
close c_test                  
deallocate c_test

*该方法适合需要按照辅助表的顺序重排table的顺序时使用
(即辅助表已经存在的情况)

方法4:分割字符串参数
select * into #tmp from table1 where 1=2 –构造临时表的结构

declare  @str  varchar(300),@id  varchar(300),@m  int,@n  int 
set  @str=2,1,4,3,      —注意后面有个逗号
set  @m=charindex(,,@str) 
set  @n=1 
while  @m>0 
begin 
       set  @id=substring(@str,@n,@m-@n) 
       –print  @id 
       insert into #tmp select id,name from table1 where id=convert(int,@id)
       set  @n=@m+1 
       set  @m=charindex(,,@str,@n) 
end 

*该方法比较有通用性

测试结果
id          name
———– —-
2           r
1           q
4           5
3           3

(所影响的行数为 4 行)

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 如何按指定的顺序获取数据-数据库专栏,SQL Server
分享到: 更多 (0)

相关推荐

  • 暂无文章