I use this code on several production systems. It is a great way to add pagescrolling into PHP/MSSQL applications. Here is my method for getting a dataset from the SP:
===============================
function DoLimitQuery( $query, $offset, $limit = 0 ) {
// make sure to escape double quotes in the query
$query = str_replace( '"', '""', $query );
$this->DoQuery( "LimitSelect \"$query\", $limit, $offset" );
$rows = array();
do {
$rows = array_merge( $rows, $this->GetRecords() );
} while ( mssql_next_result( $this->Query_ID ) );
return $rows;
}
===============================
and here is the code for the SP:
===============================
*
Created by Frederick D. Whitlark, 08/06/2001
LimitSelect is a Microsoft SQL Server T-SQL stored procedure used for returning a query result set with a limit and an offset.
Syntax:
LimitSelect query, offset, limit
Example:
LimitSelect 'Select * From users', 10, 5
This call would return 5 rows starting from the 10th row
Notes:
For offsets, the first row of the set is zero.
*/
CREATE PROCEDURE LimitSelect
@query VARCHAR (1024), -- SQL query, it'd better be a SELECT!
@ INT, -- limit the result set of the query
@offset INT -- start result set from offset
AS
-- Execute call to declare a global cursor (node_cursor) for the query passed to the SP
EXEC ('DECLARE node_cursor CURSOR GLOBAL SCROLL READ_ONLY FOR ' + @query)
-- open the global cursor declared above
OPEN node_cursor
-- tweak the starting values of limit and offset for use in the loop
SET @offset = @offset + 1
SET @limit = @limit - 1
-- advanced the cursor to the offset in the result set
FETCH ABSOLUTE @offset FROM node_cursor
-- counter i
DECLARE @i INTEGER
SET @i = 0
-- loop until limit reached by counter i
WHILE (@i < @limit)
BEGIN
-- fetch the next row in the result set and advance counter i
FETCH NEXT FROM node_cursor
SET @i = @i + 1
END
-- clean finish
CLOSE node_cursor
DEALLOCATE node_cursor