• <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>
  • 如何按指定的順序獲取數據

    發表于:2007-05-25來源:作者:點擊數: 標簽:按指定的獲取順序如何
    原貼地址: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 行)


    原文轉自:http://www.kjueaiud.com

    老湿亚洲永久精品ww47香蕉图片_日韩欧美中文字幕北美法律_国产AV永久无码天堂影院_久久婷婷综合色丁香五月

  • <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>