SQL 페이지 나누기 저장 프로세스(다중 테이블 연합 조회는 지원되지 않으며 다중 필드 정렬은 지원되지 않음)

2709 단어 저장 프로세스
CREATE PROCEDURE [dbo].[Pro_GetPageOfRecords]

@PageSize   INT=20,            --    

@CurrentPage INT,              --   

@Clumns  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)='',      --    ,      

@TotalCount INT OUTPUT ,       --                

@TotalPageCount INT OUTPUT     --              

AS

BEGIN

	DECLARE @strSql VARCHAR(5000)           --     

	DECLARE @strOrderType VARCHAR(1000)     --       

    DECLARE @SqlCount NVARCHAR(4000)   	    --     

    DECLARE @new_where VARCHAR(1000)        --    

    ----Where    -------------   	

     IF @Condition!=''

        BEGIN          

           SET @new_where = ' Where ' + @Condition                   

        END 

      ELSE

        BEGIN

            SET @new_where = ' Where 1=1'  

        END      

     ----------      ---------------

     SET @SqlCount = 'Select @TotalCount=COUNT(*),@TotalPageCount=CEILING((COUNT(*)+0.0)/'          

    +STR(@PageSize)+') FROM (Select * FROM ' + @TableName + @new_where+') AS T'                 

        BEGIN          

            EXEC SP_EXECUTESQL @SqlCount,N'@TotalCount INT OUTPUT,@TotalPageCount INT OUTPUT',       

            @TotalCount OUTPUT,@TotalPageCount OUTPUT          

        END    

    --------------    ------------      

	 IF	@BitOrderType=1   --  

	 	BEGIN

	 	    IF	@AscColumn!=''   

	 		SET @strOrderType=' ORDER BY '+@AscColumn+' DESC'

	 	    ELSE	

	 	    SET @strOrderType=' ORDER BY '+@PkColumn+' DESC'

	    END

	 ELSE  

	   BEGIN

	   IF	@AscColumn!=''

	     SET @strOrderType=' ORDER BY '+@AscColumn+' ASC'

	    ELSE	

	     SET @strOrderType=' ORDER BY '+@PkColumn+' ASC'

	   END   

-----------------    --------------------

	IF @CurrentPage=1     --   

	   BEGIN

		  SET @strSql='SELECT TOP '+STR(@PageSize)+''+@Clumns+' FROM'+ @TableName + @new_where+@strOrderType

       END	 

     ELSE               --   

       BEGIN

		  set @strsql = 'SELECT TOP '+STR(@PageSize)+' '+@Clumns+' FROM '+ @TableName + @new_where+' AND ('+@PkColumn+' NOT IN (SELECT TOP '+STR((@PageSize-1)*@PageSize)+' '+@PkColumn+' FROM '+@TableName+''+@Condition+@strOrderType+'))'+@strOrderType

       END

       

     EXEC (@strSql)

END


좋은 웹페이지 즐겨찾기