SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to architect cursor stored procedure?

Execute the following Microsoft SQL Server 2008 T-SQL script in Management Studio Query Editor to demonstrate the use of a cursor declared and opened for use inside a stored procedure.

-- T-SQL cursor stored procedure - declaring a cursor in a stored procedure

-- TRANSACT-SQL cursor local variable

USE AdventureWorks2008;

GO

 

CREATE PROCEDURE dbo.procSalesTerritory

                @TerritoryCursor CURSOR VARYING OUTPUT

AS

  SET @TerritoryCursor = CURSOR FORWARD_ONLY STATIC

                         FOR SELECT TerritoryID,

                                    Territory = Name

                             FROM   Sales.SalesTerritory

                             ORDER BY Territory;

  OPEN @TerritoryCursor;

GO

 

DECLARE  @RC INT, @TerrID INT, @TerrName VARCHAR(64)

DECLARE  @TerritoryCursor CURSOR  -- CURSOR variable

EXECUTE @RC = [AdventureWorks2008].[dbo].[procSalesTerritory]

  @TerritoryCursor OUTPUT

 

FETCH NEXT FROM @TerritoryCursor INTO @TerrID, @TerrName;

WHILE (@@FETCH_STATUS = 0)

  BEGIN

    PRINT CONVERT(varchar,@TerrID)+'  '+@TerrName

/*

9  Australia

6  Canada

3  Central

7  France

8  Germany

2  Northeast

1  Northwest

5  Southeast

4  Southwest

10  United Kingdom

 

*/

    FETCH NEXT FROM @TerritoryCursor INTO @TerrID, @TerrName;

  END;

 

CLOSE @TerritoryCursor;

 

DEALLOCATE @TerritoryCursor;

GO

DROP PROC dbo.procSalesTerritory

 

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.