.NET海量分頁數據存儲過程一

 存儲過程1

  1. CREATE PROCEDURE pagination   
  2. @tblName varchar(255), -- 表名   
  3. @strGetFields varchar(1000) = '*'-- 需要返回的列   
  4. @fldName varchar(255)=''-- 排序的字段名   
  5. @PageSize int , -- 頁尺寸   
  6. @PageIndex int-- 頁碼   
  7. @doCount bit , -- 返回記錄總數, 非 0 值則返回   
  8. @OrderType bit , -- 設置排序類型, 非 0 值則降序   
  9. @strWhere varchar(1500) = '' -- 查詢條件 (注意: 不要加 where)   
  10. AS   
  11. declare @strSQL varchar(5000) -- 主語句   
  12. declare @strTmp varchar(110) -- 臨時變量   
  13. declare @strOrder varchar(400) -- 排序類型   
  14.  
  15. if @doCount != 0   
  16. begin   
  17. if @strWhere !=''   
  18. set @strSQL = "select count(*) as Total from [" + @tblName + "] where "+@strWhere   
  19. else   
  20. set @strSQL = "select count(*) as Total from [" + @tblName + "]"   
  21. end   
  22. --以上代碼的意思是如果@doCount傳遞過來的不是0,就執行總數統計。以下的所有代碼都是@doCount爲0的情況   
  23. else   
  24. begin   
  25.  
  26. if @OrderType != 0   
  27. begin   
  28. set @strTmp = "<(select min"   
  29. set @strOrder = " order by [" + @fldName +"] desc"   
  30. --如果@OrderType不是0,就執行降序,這句很重要!   
  31. end   
  32. else   
  33. begin   
  34. set @strTmp = ">(select max"   
  35. set @strOrder = " order by [" + @fldName +"] asc"   
  36. end   
  37.  
  38. if @PageIndex = 1   
  39. begin   
  40. if @strWhere != ''   
  41. set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from [" + @tblName + "] where " + @strWhere + " " + @strOrder   
  42. else   
  43. set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["+ @tblName + "] "+ @strOrder   
  44. --如果是第一頁就執行以上代碼,這樣會加快執行速度   
  45. end   
  46. else   
  47. begin   
  48. --以下代碼賦予了@strSQL以真正執行的SQL代碼   
  49. set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["   
  50. + @tblName + "] where [" + @fldName + "]" + @strTmp + "(["+ @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["+ @fldName + "] from [" + @tblName + "]" + @strOrder + ") as tblTmp)"+ @strOrder   
  51.  
  52. if @strWhere != ''   
  53. set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ " from ["   
  54. + @tblName + "] where [" + @fldName + "]" + @strTmp + "(["   
  55. + @fldName + "]) from (select top " + str((@PageIndex-1)*@PageSize) + " ["   
  56. + @fldName + "] from [" + @tblName + "] where " + @strWhere + " "   
  57. + @strOrder + ") as tblTmp) and " + @strWhere + " " + @strOrder   
  58. end   
  59. end   
  60. exec (@strSQL)  
  61. GO  

 

原文鏈接:http://www.cnblogs.com/wdy6279/archive/2011/04/29/2032448.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章