按指定排列順序獲取數據的sql語句_Mssql數據庫教程
推薦:總結經典常用的SQL語句(2)向表中添加一個新記錄,你要使用SQLINSERT語句。 這里有一個如何使用這種語句的例子: INSERTmytable(mycolumn)VALUES(‘somedata’) 這個語句把字符串’somedata’插入表mytable的mycolumn字段中。將要被插入數據的字段的名字在第一個括號中指定,實際的數
測試tablecreate 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的順序時使用
(即輔助表已經存在的情況)
分享:總結經典常用的SQL語句(1)說明:復制表(只復制結構,源表名:a新表名:b) SQL:select*intobfromawhere11 說明:拷貝表(拷貝數據,源表名:a目標表名:b) SQL:insertintob(a,b,c)selectd,e,ffromb; 說明:顯示文章、提交人和最后回復時間 SQL:selecta.title,a.username,b.adddatefromtab
- sql 語句練習與答案
- 深入C++ string.find()函數的用法總結
- SQL Server中刪除重復數據的幾個方法
- sql刪除重復數據的詳細方法
- SQL SERVER 2000安裝教程圖文詳解
- 使用sql server management studio 2008 無法查看數據庫,提示 無法為該請求檢索數據 錯誤916解決方法
- SQLServer日志清空語句(sql2000,sql2005,sql2008)
- Sql Server 2008完全卸載方法(其他版本類似)
- sql server 2008 不允許保存更改,您所做的更改要求刪除并重新創建以下表
- SQL Server 2008 清空刪除日志文件(瞬間日志變幾M)
- Win7系統安裝MySQL5.5.21圖解教程
- 將DataTable作為存儲過程參數的用法實例詳解
- 相關鏈接:
- 教程說明:
Mssql數據庫教程-按指定排列順序獲取數據的sql語句
。