全面的儲存過程 測試可用

lanchengxiaoxiao發表於2012-05-04
USE [Studentnew]
GO
/******
分頁,呼叫例子如下
exec dbo.cs_GetPageOfRecords 2,1,'*','a','1=1','id',1,'id'
輸入引數:每頁2條,第1頁,得到所有欄位顯示出來,表a,查詢條件1=1
根據id降序排列,主鍵id
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--建立儲存過程
ALTER PROCEDURE [dbo].[cs_GetPageOfRecords]
  @pageSize int = 20,                         --分頁大小
  @currentPage int ,                          --第幾頁
  @columns varchar(1000) = '*',               --需要得到的欄位
  @tableName varchar(100),                    --需要查詢的表    
  @condition varchar(1000) = '',              --查詢條件, 不用加where關鍵字
  @ascColumn varchar(100) = '',               --排序的欄位名 (即 order by column asc/desc)
  @bitOrderType bit = 0,                      --排序的型別 (0為升序,1為降序)
  @pkColumn varchar(50) = ''                  --主鍵名稱

AS
BEGIN                                         --儲存過程開始
  DECLARE @strTemp varchar(300)
  DECLARE @strSql varchar(5000)               --該儲存過程最後執行的語句
  DECLARE @strOrderType varchar(1000)         --排序型別語句 (order by column asc或者order by column desc)

  BEGIN
    IF @bitOrderType = 1                --降序
      BEGIN
        SET @strOrderType = ' ORDER BY '+@ascColumn+' DESC'
        SET @strTemp = '<(SELECT min'
      END
    ELSE                  --升序
      BEGIN
        SET @strOrderType = ' ORDER BY '+@ascColumn+' ASC'
        SET @strTemp = '>(SELECT max'
      END

    IF @currentPage = 1            --第一頁
      BEGIN
        IF @condition != ''
          SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+
            ' WHERE '+@condition+@strOrderType
        ELSE
          SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+@strOrderType
      END

    ELSE                  -- 其他頁
      BEGIN
        IF @condition !=''
          SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+
          ' WHERE '+@condition+' AND '+@pkColumn+@strTemp+'('+@pkColumn+')'+' FROM (SELECT TOP '+STR((@currentPage-1)*@pageSize)+
          ' '+@pkColumn+' FROM '+@tableName +'where'+@condition+@strOrderType+') AS TabTemp)'+@strOrderType
        ELSE
          SET @strSql = 'SELECT TOP '+STR(@pageSize)+' '+@columns+' FROM '+@tableName+
          ' WHERE '+@pkColumn+@strTemp+'('+@pkColumn+')'+' FROM (SELECT TOP '+STR((@currentPage-1)*@pageSize)+' '+@pkColumn+
          ' FROM '+@tableName+@strOrderType+') AS TabTemp)'+@strOrderType
      END

  END
  EXEC (@strSql)
END 

相關文章