All articles| All Pictures| All Softwares| All Video| Go home page| Write articles| Upload pictures

Reading number is top 10 articles
asp.net2.0中水晶报表的应用实例
C#箴言:使用构造函数初始化语句_.net资料_编程技术
Apache指南-,.htaccess文件使用手册_php资料_编程技术
ASP.NET技巧:DataGrid的多行提交_[Asp.Net教程]
URL重写可删节日期模式--
ASP.NET,网站路径_[Asp.Net教程]
php5.0升级5.2全过程_php资料_编程技术
详细介绍动态网页PHP预定义变量之服务器变量_php资料_编程技术
SQL Server和Oracle常用函数区别_[SQL Server教程]
解决SQL Server 2000中讨厌的Bug_[SQL Server教程]
Reading number is top 10 pictures
XuRe xuan cool and refreshing photoes2
China's ambassador to Libya embassy was shock, and the glass is broken in
青春清纯美女大集合1
做运动的校花2
More attractive than sora aoi1
8090后结婚的各种XX事
西游日记2
The terra-cotta warriors3
青春清纯美女大集合2
The terra-cotta warriors1
Download software ranking
The cock of the Grosvenor LTD handsome
Ashlynn Video5
WebService在.NET中的实战应用教学视频 → 第3集
传奇私服架设教程
Unix video tutorial2
Boxer Classic video3
Ashlynn Video2
Unix video tutorial18
Take off clothes to survival
DreamWeaver8
归海一刀 published in(发表于) 2014/2/3 6:45:21 Edit(编辑)
按指定排列顺序获取数据的sql语句_[SQL Server教程]

按指定排列顺序获取数据的sql语句_[SQL Server教程]

按指定排列顺序获取数据的sql语句_[SQL Server教程]
测试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的顺序时使用
(即辅助表已经存在的情况)





添加到del.icio.us 添加到新浪ViVi 添加到百度搜藏 添加到POCO网摘 添加到天天网摘365Key 添加到和讯网摘 添加到天极网摘 添加到黑米书签 添加到QQ书签 添加到雅虎收藏 添加到奇客发现 diigo it 添加到饭否 添加到飞豆订阅 添加到抓虾收藏 添加到鲜果订阅 digg it 貼到funP 添加到有道阅读 Live Favorites 添加到Newsvine 打印本页 用Email发送本页 在Facebook上分享


Disclaimer Privacy Policy About us Site Map

If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.