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

首頁(yè) > 開(kāi)發(fā) > 綜合 > 正文

如何按指定的順序獲取數(shù)據(jù)

2024-07-21 02:05:55
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
  • 網(wǎng)站運(yùn)營(yíng)seo文章大全
  • 提供全面的站長(zhǎng)運(yùn)營(yíng)經(jīng)驗(yàn)及seo技術(shù)!

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

    測(cè)試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的數(shù)據(jù)

    方法1:使用union all,但是有256條數(shù)據(jù)的限制
    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)

    *以上兩種方法適合在數(shù)據(jù)量非常小的情況下使用

    方法3:使用游標(biāo)和臨時(shí)表
    先建一個(gè)輔助表,里面你需要的順序插入,比如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                              --定義游標(biāo)
    declare c_test cursor for
    select id from t1                       

    select * into #tmp from table1 where 1=2     --構(gòu)造臨時(shí)表的結(jié)構(gòu)

    open c_test

    fetch next from c_test
    into @id
    while @@fetch_status = 0
    begin
    --按t1中的id順序插數(shù)據(jù)到臨時(shí)表
    insert into #tmp select id,name from table1 where [email protected]  
    fetch next from c_test  into @id
    end
    close c_test                  
    deallocate c_test

    *該方法適合需要按照輔助表的順序重排table的順序時(shí)使用
    (即輔助表已經(jīng)存在的情況)

    方法4:分割字符串參數(shù)
    select * into #tmp from table1 where 1=2 --構(gòu)造臨時(shí)表的結(jié)構(gòu)

    declare  @str  varchar(300),@id  varchar(300),@m  int,@n  int 
    set  @str='2,1,4,3,'      ---注意后面有個(gè)逗號(hào)
    set  @m=charindex(',',@str) 
    set  @n=1 
    while  @m>0 
    begin 
           set  @id=substring(@str,@n,@[email protected]) 
           --print  @id 
           insert into #tmp select id,name from table1 where id=convert(int,@id)
           set  @[email protected]+1 
           set  @m=charindex(',',@str,@n) 
    end 

    *該方法比較有通用性

    測(cè)試結(jié)果
    id          name
    ----------- ----
    2           r
    1           q
    4           5
    3           3

    (所影響的行數(shù)為 4 行)

    發(fā)表評(píng)論 共有條評(píng)論
    用戶名: 密碼:
    驗(yàn)證碼: 匿名發(fā)表
    主站蜘蛛池模板: 襄樊市| 昌都县| 从化市| 延寿县| 咸宁市| 旺苍县| 仙桃市| 河池市| 海淀区| 诸城市| 鹿泉市| 七台河市| 南溪县| 香港| 信丰县| 桓台县| 澳门| 新宁县| 玛多县| 盱眙县| 宿迁市| 军事| 祁东县| 南投市| 新密市| 潼关县| 莲花县| 鄱阳县| 岳阳市| 乐陵市| 扎鲁特旗| 青海省| 东乌珠穆沁旗| 江口县| 凌云县| 麻江县| 仪征市| 大渡口区| 宿迁市| 宿迁市| 铁岭县|