日韩天天综合网_野战两个奶头被亲到高潮_亚洲日韩欧美精品综合_av女人天堂污污污_视频一区**字幕无弹窗_国产亚洲欧美小视频_国内性爱精品在线免费视频_国产一级电影在线播放_日韩欧美内地福利_亚洲一二三不卡片区

按指定排列順序獲取數(shù)據(jù)的sql語句_Mssql數(shù)據(jù)庫教程

編輯Tag賺U幣
教程Tag:暫無Tag,歡迎添加,賺取U幣!

推薦:總結(jié)經(jīng)典常用的SQL語句(2)
向表中添加一個新記錄,你要使用SQLINSERT語句。 這里有一個如何使用這種語句的例子: INSERTmytable(mycolumn)VALUES(‘somedata’) 這個語句把字符串’somedata’插入表mytable的mycolumn字段中。將要被插入數(shù)據(jù)的字段的名字在第一個括號中指定,實際的數(shù)

測試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)和臨時表
先建一個輔助表,里面你需要的順序插入,比如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)造臨時表的結(jié)構(gòu)

OPEN c_test

FETCH NEXT FROM c_test
INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
--按t1中的id順序插數(shù)據(jù)到臨時表
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的順序時使用
(即輔助表已經(jīng)存在的情況)

分享:總結(jié)經(jīng)典常用的SQL語句(1)
說明:復(fù)制表(只復(fù)制結(jié)構(gòu),源表名:a新表名:b) SQL:select*intobfromawhere11 說明:拷貝表(拷貝數(shù)據(jù),源表名:a目標(biāo)表名:b) SQL:insertintob(a,b,c)selectd,e,ffromb; 說明:顯示文章、提交人和最后回復(fù)時間 SQL:selecta.title,a.username,b.adddatefromtab

共2頁上一頁12下一頁
來源:模板無憂//所屬分類:Mssql數(shù)據(jù)庫教程/更新時間:2010-04-09
相關(guān)Mssql數(shù)據(jù)庫教程