国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

按指定排列順序獲取數據的sql語句

2024-08-31 00:46:56
字體:
來源:轉載
供稿:網友
測試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的順序時使用
(即輔助表已經存在的情況)

共2頁上一頁12下一頁
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 修武县| 怀柔区| 栾川县| 荣成市| 苏尼特左旗| 黔南| 乐亭县| 宝应县| 清苑县| 泰顺县| 汝南县| 喀什市| 长宁区| 绥中县| 河北区| 赫章县| 涪陵区| 昌宁县| 漳浦县| 凉城县| 哈密市| 师宗县| 鄂伦春自治旗| 盐源县| 天津市| 页游| 定兴县| 连山| 朝阳区| 宁河县| 城步| 精河县| 稻城县| 石阡县| 全椒县| 潞西市| 绥德县| 扎鲁特旗| 武汉市| 嵊泗县| 诸暨市|