Thursday, 4 October 2007

Stored procedure using Cursors

the below is a sample example for stored procedure and cursors
CREATE PROCEDURE prcCursorExample
AS

-- declare all variables!

DECLARE @iRowId int,
@vchCustomerName nvarchar(255),
@vchCustomerNmbr nvarchar(10)

-- declare the cursor
DECLARE Customer CURSOR FOR
SELECT iRowId,
vchCustomerNmbr,
vchCustomerName
FROM CustomerTable

OPEN Customer

FETCH Customer INTO @iRowId,
@vchCustomerNmbr,
@vchCustomerName


-- start the main processing loop.
WHILE @@Fetch_Status = 0

BEGIN

-- This is where you perform your detailed row-by-row processing. INSERT INTO ORDER(CUSTOMERNUMBER,CUSTOMERNAME) values(@vchCustomerNmbr,@vchCustomerName)

-- Get the next row.
FETCH Customer INTO @iRowId,
@vchCustomerNmbr,
@vchCustomerName
END

CLOSE Customer
DEALLOCATE Customer
RETURN

No comments: