本篇文章为大家展示了SQLServer分页存储过程有哪些,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
SQLServer分页存储过程有哪几种方法
创建数据库data_Test:
createdatabasedata_TestGOusedata_TestGOcreatetabletb_TestTable--创建表(idintidentity(1,1)primarykey,userNamenvarchar(20)notnull,userPWDnvarchar(20)notnull,userEmailnvarchar(40)null)GO
插入数据:
setidentity_inserttb_TestTableondeclare@countintset@count=1while@count<=2000000begininsertintotb_testtable(id,username,userpwd,useremail)values(@count,'admin','admin888','lli0077@yahoo.com.cn count="@count+1endsetidentity_inserttb_TestTableoff" timediff="Getdate()set@sql='selecttop'+str(@pageSize)+'*Fromtb_TestTablewhere(ID">(selectmax(id)From(selecttop'+str(@pageSize*@pageIndex)+'idFromtb_TestTableorderbyID)asTempTable))orderbyID'execute(@sql)selectdatediff(ms,@timediff,GetDate())as耗时setnocountoff;end
SQLServer分页存储过程有哪几种方法
3、利用selecttop和中间变量
createprocedureproc_paged_with_Midvar--利用ID>最大ID值和中间变量(@pageIndexint,@pageSizeint)asdeclare@countintdeclare@IDintdeclare@timediffdatetimedeclare@sqlnvarchar(500)beginsetnocounton;select@count=0,@ID=0,@timediff=getdate()select@count=@count+1,@ID=casewhen@count<=@pagesize*@pageindexthenidelse@idendfromtb_testtableorderbyidset@sql='selecttop'+str(@pagesize)+'*fromtb_testtablewhereid>'+str(@ID)execute(@sql)selectdatediff(ms,@timediff,getdate())as耗时setnocountoff;end
4、利用Row_number()此方法为SQLserver2005中新的方法,利用Row_number()给数据行加上索引
createprocedureproc_paged_with_Rownumber--利用SQL2005中的Row_number()(@pageIndexint,@pageSizeint)asdeclare@timediffdatetimebeginsetnocounton;select@timediff=getdate()select*from(select*,Row_number()over(orderbyIDasc)asIDRankfromtb_testTable)asIDWithRowNumberwhereIDRank>@pageSize*@pageIndexandIDRank<@pageSize*(@pageIndex+1)selectdatediff(ms,@timediff,getdate())as耗时setnocountoff;end
5、利用临时表及Row_number createprocedureproc_CTE--利用临时表及Row_number(@pageIndexint,--页索引@pageSizeint--页记录数)assetnocounton;declare@ctestrnvarchar(400)declare@strSqlnvarchar(400)declare@datediffdatetimebeginselect@datediff=GetDate()set@ctestr='withTable_CTEas(selectceiling((Row_number()over(orderbyIDASC))/'+str(@pageSize)+')aspage_num,*fromtb_TestTable)';set@strSql=@ctestr+'select*FromTable_CTEwherepage_num='+str(@pageIndex)endbeginexecutesp_executesql@strSqlselectdatediff(ms,@datediff,GetDate())setnocountoff;end
上述内容就是SQLServer分页存储过程有哪些,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。