–建立主表臨時(shí)表
CREATE TABLE #temp
(
rownumber bigint,
orderseqno VARCHAR(36),
goodsname VARCHAR(50),
companyname VARCHAR(100)
)
–建立子表臨 時(shí)表
CREATE TABLE #detail
(
orderseqno VARCHAR(36),
detailid UNIQUEIDENTIFIER,
unitprice DECIMAL(12,2),
Qty int
)
–插入主表數(shù)據(jù)到主表臨時(shí)表
insert into #temp
SELECT oo.rownumber, oo.OrderSeqNO, oo.GoodsName, oo.CompanyName FROM
(SELECT ROW_NUMBER () OVER (ORDER BY oi.createdate DESC) AS rownumber,
oi.OrderSeqNO, oi.GoodsName ,ci.CompanyName
FROM OrderInfo oi INNER JOIN CompanyInfo ci ON oi.CompanyID=ci.CompanyID
WHERE oi.CreateDateGETDATE()
) AS oo
WHERE rownumber BETWEEN 10 AND 20
–定義游標(biāo)
DECLARE @temp_cursor CURSOR
–給游標(biāo)賦值
SET @temp_cursor=CURSOR FOR SELECT #temp.orderseqno,#temp.goodsname FROM #temp
–定義游標(biāo)循環(huán)過(guò)程中所需保存的臨時(shí)數(shù)據(jù)
DECLARE @orderseqno VARCHAR(36),@goodsname varchar(50)
–打開(kāi)游標(biāo)
OPEN @temp_cursor
FETCH NEXT FROM @temp_cursor INTO @orderseqno,@goodsname
–循環(huán)游標(biāo),查詢(xún)子表數(shù)據(jù),然后插入子表臨時(shí)表
WHILE @@FETCH_STATUS=0
BEGIN
INSERT INTO #detail
SELECT od.OrderSeqNO,od.OrderDetailID, od.UnitPrice,od.Qty
FROM OrderDetail od
WHERE od.OrderSeqNO=@orderseqno
FETCH NEXT FROM @temp_cursor INTO @orderseqno,@goodsname
END
–關(guān)閉游標(biāo)
CLOSE @temp_cursor
DEALLOCATE @temp_cursor
SELECT * FROM #temp
SELECT * FROM #detail
–刪除臨時(shí)表
DROP TABLE #temp
DROP TABLE #detail
上面的T-SQL只在SQL Server 2005上調(diào)試成功。
您可能感興趣的文章:- 五種SQL Server分頁(yè)存儲(chǔ)過(guò)程的方法及性能比較
- SQL Server 分頁(yè)查詢(xún)通用存儲(chǔ)過(guò)程(只做分頁(yè)查詢(xún)用)
- sqlserver2005利用臨時(shí)表和@@RowCount提高分頁(yè)查詢(xún)存儲(chǔ)過(guò)程性能示例分享
- 基于Sql Server通用分頁(yè)存儲(chǔ)過(guò)程的解決方法
- mssql 高效的分頁(yè)存儲(chǔ)過(guò)程分享
- SQL Server 2005通用分頁(yè)存儲(chǔ)過(guò)程及多表聯(lián)接應(yīng)用
- MSSQL MySQL 數(shù)據(jù)庫(kù)分頁(yè)(存儲(chǔ)過(guò)程)
- 三種SQL分頁(yè)查詢(xún)的存儲(chǔ)過(guò)程代碼
- SQL通用存儲(chǔ)過(guò)程分頁(yè),支持多表聯(lián)合
- SQL分頁(yè)查詢(xún)存儲(chǔ)過(guò)程代碼分享