加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 电商 > 正文

怎样按指定的次序获取数据

发布时间:2018-08-18 11:44:57 所属栏目:电商 来源:站长网
导读:原贴地点: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' 要求按指

原贴地点: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 行)

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读