SET @op = '<' SET @max_min = 'MIN' IF @sort = 'asc' BEGIN SET @Op = '>' SET @max_min = 'MAX' END
SET @uprecord=@curpage * @page_record
IF @curpage = 0 SET @cmd = 'SELECT TOP '+cast(@page_record AS NVARCHAR)+' '+@fieldlist+' FROM '+@tablename+' WHERE '+@where+' '+@orderby ELSE SET @cmd = 'SELECT TOP '+cast(@page_record AS NVARCHAR)+' '+@fieldlist+' FROM '+@tablename+' WHERE '+@where+' AND '+@tablefield+' '+@op+' (SELECT '+@max_min+'('+@tablefield+') FROM (SELECT TOP '+cast(@uprecord AS NVARCHAR)+' '+@tablefield+' FROM '+@tablename+' WHERE '+@where+' '+@orderby+') AS TmpTbl ) AND '+@where+' '+@orderby
SET @cmd = @cmd + '; SELECT COUNT(*) FROM '+@tablename+' WHERE '+@where