Skip to content

Instantly share code, notes, and snippets.

@aykuttasil
Created August 4, 2016 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aykuttasil/b772e7f9eda20c551e22dcabb62592f3 to your computer and use it in GitHub Desktop.
Save aykuttasil/b772e7f9eda20c551e22dcabb62592f3 to your computer and use it in GitHub Desktop.
SQL CURSOR
USE [colombo]
GO
-- drop prev version
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = N'pco_cursor_test1'
AND type = 'P')
DROP PROCEDURE pco_cursor_test1
GO
-- create new
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* ==============================================================
Author: [ amper ]
Create date: [ 2007-10-12 ]
Description: [demo procedure for updating delivery prices
in Invoices table using CURSOR]
================================================================ */
CREATE PROCEDURE dbo.pco_cursor_test1
AS
BEGIN
DECLARE @docno INT, @country NVarchar(50), @city NVarchar(50)
/*
define cursor on the join between Invoice and Customers tables
*/
DECLARE invoice_cursor CURSOR FOR
SELECT a.DocNo, b.Country, b.City
FROM dbo.Invoice AS a INNER JOIN dbo.Customers AS b
ON a.CustomerID = b.CustomerID
GROUP BY a.DocNo, b.Country, b.City;
OPEN invoice_cursor /* open cursor */
FETCH NEXT FROM invoice_cursor
INTO @docno, @country, @city;
/* cursor loop */
WHILE (@@FETCH_STATUS <> -1)
BEGIN
/* execute function that returns delivery price for
given location. write results to Invoice table */
UPDATE dbo.Invoice
SET DlvPrice = dbo.fn_getdeliveryprice(@country, @city)
WHERE DocNo = @docno;
-- move to the next record
FETCH NEXT FROM invoice_cursor
INTO @docno, @country, @city
END
/* release data structures that was allocated by cursor */
CLOSE invoice_cursor;
DEALLOCATE invoice_cursor;
-- end of procedure
END
GO
GRANT EXECUTE ON OBJECT::dbo.pco_cursor_test1 TO george;
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment