Frederick writes "I have the following stored procedure for iterating through a SELECT result set and returning records based on a 'limit' and offset'. Here is the SP code:-------------------------CREATE PROCEDURE LimitSelect @query CHAR (128), -- SQL query, it'd better be a SELECT! @limit INT, -- limit the result set of the query @offset INT -- start result set from offsetAS -- 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-------------------------This stored procedure works fine in most cases, but if the WHERE clause of the SELECT query passed to the SP becomes too complex, the cursor declaration in the SP tends to fail without explanation. I was wondering if you know why it is failing and how to prevent it from doing so. Here is an example that creates a curor declaration failure:LimitSelect ' SELECT * FROM news WHERE cat_id in(10, 11) AND is_disabled=0 AND (news_date BETWEEN 978328800 AND 1009864799 ) ORDER BY news_date DESC ', 5, 1
However, removing one WHERE condition will enable the procedure to execute properly:LimitSelect ' SELECT * FROM news WHERE cat_id in(10, 11) AND (news_date BETWEEN 978328800 AND 1009864799 ) ORDER BY news_date DESC ', 5, 1
Any thoughts on why this is? I'm working with SQL Server 7.0, BTW."