SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Returning a Subset of a Recordset

By Jon Winer, 2003/08/29

Total article views: 9938 | Views in the last 30 days: 8
Returning a Subset of a Recordset
Stateless programming can be tricky... In case you ever need to return a specified subset of a query without first returning the entire recordset, here's a method.  (This tip was given to me by a co-worker, Jason Rice).

CREATE PROCEDURE

sp_GetOrders(@subset int = 0, @rowcount int = 10, @orderby varchar(100) = 'OrderDate')

AS

--Use the Northwind Database for this example

BEGIN

SET NOCOUNT ON

DECLARE @ABSPOS INT
SET @ABSPOS = @SUBSET * @ROWCOUNT + 1

CREATE TABLE
#ORDERS
(OrderDate DATETIME, ShipName VARCHAR(50), ShipCity VARCHAR(50))

DECLARE
@OrderDate DATETIME,
@ShipName VARCHAR(50),
@ShipCity VARCHAR(50)

EXEC('DECLARE cOrders SCROLL CURSOR FOR
SELECT OrderDate, ShipName, ShipCity FROM Orders ORDER BY ' + @orderby)
OPEN cOrders

DECLARE @COUNTER INT
SET @COUNTER = 0
FETCH ABSOLUTE @ABSPOS FROM cOrders INTO @OrderDate, @ShipName, @ShipCity

WHILE( @@FETCH_STATUS = 0 AND @COUNTER < @ROWCOUNT)
BEGIN
INSERT #ORDERS VALUES(@OrderDate, @ShipName, @ShipCity)
SET @COUNTER = @COUNTER + 1
FETCH FROM cOrders INTO @OrderDate, @ShipName, @ShipCity
END

CLOSE cOrders
DEALLOCATE cOrders

SELECT * FROM #ORDERS

SET NOCOUNT OFF
END
GO

By Jon Winer, 2003/08/29

Total article views: 9938 | Views in the last 30 days: 8
Your response
 
 
Related tags

Advanced Querying    
T-SQL    
 
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com