SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[EoyooCorp_Proc_Page]
 @TableName nvarchar(50),
 @Fields nvarchar(4000) = '*',
 @OrderField nvarchar(4000),
 @sqlWhere nvarchar(4000) = Null,
 @pageSize int,
 @pageIndex int = 1,
 @totalRecord int output,
 @TotalPage int output
as
begin
    Begin Tran
    Declare @sql nvarchar(4000);
    if (@SqlWhere='' or @sqlWhere=NULL)
        set @sql = 'select @totalRecord = count(*) from ' + @TableName
    else
        set @sql = 'select @totalRecord = count(*) from ' + @TableName + ' where ' + @sqlWhere
    EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT    
    select @TotalPage=CEILING((@totalRecord+0.0)/@PageSize)
    if (@SqlWhere='' or @sqlWhere=NULL)
        set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField + ') as rowId,' + @Fields + ' from ' + @TableName 
    else
        set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField + ') as rowId,' + @Fields + ' from ' + @TableName + ' where ' + @SqlWhere 
    if @PageIndex<=0 
        Set @pageIndex = 1
    if @pageIndex>@TotalPage
        Set @pageIndex = @TotalPage
    Declare @StartRecord int
    Declare @EndRecord int
    set @StartRecord = (@pageIndex-1)*@PageSize + 1
    set @EndRecord = @StartRecord + @pageSize - 1
    set @Sql = @Sql + ') as ' + @TableName + ' where rowId between ' + Convert(nvarchar(50),@StartRecord) + ' and ' +  Convert(nvarchar(50),@EndRecord)
    Exec(@Sql)
    If @@Error <> 0
      Begin
        RollBack Tran
        Return -1
      End
     Else
      Begin
        Commit Tran
        Return @totalRecord
      End    
end
