注册 | 登录
收藏 | 帮助
热门文章
编辑推荐
相关文章  
如何根据名称识别计算机病毒
教你如何防止脚本病毒执行的通用
在网吧如何防止病毒和快速杀毒
如何判断电脑是否感染了病毒
特络伊木马如何利用文件关联和设
深入揭秘木马是如何盗取QQ密码的
如何知道你的电脑是否含有病毒
杀毒软件如何被XP SP2的安全中心
教你如何手工剿灭QQ广告弹出的木
木马是如何编写的(一)
您现在的位置: 顶尖设计 >> IT学院 >> 数据库 >> MS SQL >> 文章正文
如何按指定的顺序获取数据
作者:NinGoo  来源:CSDN  点击:  更新:2006-12-20
简介:

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




  • 上一篇文章:
  • 下一篇文章:
  • 分享此文:该页面添加到 Mister Wong 添加到雅虎Yahoo!收藏 Add to:Del.icio.us Post to Furl Digg this 添加到Google书签 reddit spurl blogmarks 365Key 评论  收藏  分享  打印
     我来说两句
    姓名:       验证码:   
    主页: 
    评分: 1分 2分 3分 4分 5分
    本频道近期热评文章:
      关于我们 | 联系我们 | 站点地图 | 广告投放 | 友情链接 | 在线留言 | 版权申明
    版权所有 © 2004-2007 顶尖设计(bobd.cn)
    未经授权禁止转载,摘编,复制本站内容或建立镜像. 沪ICP备07504942号 
    网络110
    报警服务