深入sql server 2005 万能分页存储过程的详解
?C建立主表临时表
CREATE TABLE #temp
(
rownumber bigint,
orderseqno VARCHAR(36),
goodsname VARCHAR(50),
companyname VARCHAR(100)
)
?C建立子表临 时表
CREATE TABLE #detail
(
orderseqno VARCHAR(36),
detailid UNIQUEIDENTIFIER,
unitprice DECIMAL(12,2),
Qty int
)
?C插入主表数据到主表临时表
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.CreateDate<GETDATE()
) AS oo
WHERE rownumber BETWEEN 10 AND 20
?C定义游标
DECLARE @temp_cursor CURSOR
?C给游标赋值
SET @temp_cursor=CURSOR FOR SELECT #temp.orderseqno,#temp.goodsname FROM #temp
?C定义游标循环过程中所需保存的临时数据
DECLARE @orderseqno VARCHAR(36),@goodsname varchar(50)
?C打开游标
OPEN @temp_cursor
FETCH NEXT FROM @temp_cursor INTO @orderseqno,@goodsname
?C循环游标,查询子表数据,然后插入子表临时表
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
?C关闭游标
CLOSE @temp_cursor
DEALLOCATE @temp_cursor
SELECT * FROM #temp
SELECT * FROM #detail
?C删除临时表
DROP TABLE #temp
DROP TABLE #detail
上面的T-SQL只在SQL Server 2005上调试成功。
栏 目:MsSql
下一篇:SQL学习笔记一SQL基础知识
本文标题:深入sql server 2005 万能分页存储过程的详解
本文地址:http://www.codeinn.net/misctech/27290.html