set @TableName=' '+@TableName+' ' set @key=' '+@key+' '
if @order='0' set @ordreby=' order by '+@key+'desc' else set @ordreby=' order by '+@key
if @where='null' set @sql='select @count = count(*) from '+ @TableName else set @sql='select @count = count(*) from '+ @TableName+' where '+@where
------------@count 付值(聲明變量@count 在說明是output 內型)--------------------------- exec sp_executesql @sql,N'@count int out',@count out ------------求總頁數------------------------------ if (@count%@pagesize)=0 set @pagecount=@count/@pagesize else set @pagecount=@count/@pagesize+1 -----------判斷顯示當前頁是否異常------------------ if @currentpage>@pagecount set @currentpage=@pagecount if @currentpage<1 set @currentpage=1 ----------記錄數小于頁面顯示記錄數----------------- if(@currentpage=1) begin if @where='null' set @where=' ' else set @where=' where '+@where set @sql = 'select top'+ str(@pagesize)+' * from '+@TableName+@where+@ordreby end else begin /**//* ---------------desc---------------------- *@temp1表示前面的記錄 *@temp2表示后面的記錄 *假設一共77個記錄,每次取10個。取67~58(第2頁),去掉前面的57(1~57)個和后面的10個(77~66) */ if @order=0 begin set @temp1 = @count-@currentpage*@pagesize if @temp1<0 set @temp1=0 set @temp2 = (@currentpage - 1)*@pagesize if @where='null' begin set @tempsql1='select top ' + str(@temp1)+' '+@key+' from ' + @TableName+' order by ' +@key set @tempsql2='select top ' + str(@temp2)+' '+@key+' from ' + @TableName + @ordreby end else begin set @tempsql1='select top ' + str(@temp1)+' '+@key+' from ' + @TableName+' where '+@where+' order by ' +@key set @tempsql2='select top ' + str(@temp2)+' '+@key+' from ' + @TableName+' where '+@where+@ordreby end set @sql=' select top ' + str(@pagesize) + ' * from ' + @TableName + ' where '+@key+ ' not in ' set @sql= @sql+' ( '+ @tempsql1 +' ) and ' set @sql= @sql+@key+ ' not in ( '+@tempsql2 +' ) ' if @where='null' set @sql= @sql+@ordreby else set @sql= @sql+' and '+@where+@ordreby end /**//* ----------------asc--------------------- * @temp 表示前面顯示的記錄總數 * 去掉 @temp 在取出 pagesize 個即可 */ else begin set @temp1=(@currentpage-1)*@pagesize if @where='null' set @tempsql1='select top '+ str(@temp1)+' '+@key+' from ' + @TableName + @ordreby else set @tempsql1='select top '+ str(@temp1)+' '+@key+' from ' + @TableName ++' where '+@where+@ordreby set @sql=' select top ' + str(@pagesize) + ' * from ' + @TableName + ' where '+@key+ ' not in ' set @sql=@sql+' ( '+@tempsql1+' ) ' if @where='null' set @sql= @sql+@ordreby else set @sql= @sql+' and '+@where+@ordreby
end /**//* -------------------------------------*/ end set @str=@sql --exec sp_executesql @sql