liveBook · Manning

Close

As explained in Learn SQL in a Month of Lunches

CLOSE is a cursor operation that terminates cursor use and releases its associated resources.

CLOSE is the final cursor step. After a cursor has been opened and its rows fetched, CLOSE ends cursor use and releases the cursor contents from server memory. section 22.2.1

Place CLOSE at the end of the cursor’s work:

Closing a cursor in a stored procedure

After the GetOrders loop finishes, the procedure uses CLOSE AllOrders;. The loop has already fetched each OrderID and added qualifying title quantities; CLOSE now releases the cursor’s contents from memory. The procedure then ends, and its output can be inspected by calling it and selecting @TotalQuantitySold. section 22.2.2

DELIMITER //
 
CREATE PROCEDURE GetTitleTotalQuantitySoldListPrice(
    OUT _TotalQuantitySold int
    )
BEGIN
 
DECLARE _Done boolean DEFAULT FALSE;
 
DECLARE _OrderID int;
 
DECLARE AllOrders CURSOR FOR
 
SELECT OrderID
FROM orderheader;
 
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _Done = TRUE;
 
SET _TotalQuantitySold = 0;
 
OPEN AllOrders;
 
GetOrders: LOOP
 
    FETCH AllOrders INTO _OrderID;
 
    SET _TotalQuantitySold = _TotalQuantitySold +
 
        (SELECT COALESCE(SUM(Quantity),0)
        FROM title t
        INNER JOIN orderitem oi
             ON t.TitleID = oi.TitleID
             AND t.Price = oi.ItemPrice
        WHERE oi.OrderID = _OrderID
        );
 
        IF _Done = TRUE THEN
 
            LEAVE GetOrders;
        END IF;
 
    END LOOP GetOrders;
 
    CLOSE AllOrders;
 
END //
 
DELIMITER ;

Browse the complete MySQL stored procedure to see CLOSE AllOrders placed after END LOOP and before END. section 22.2.2

How Learn SQL in a Month of Lunches covers it

How deep it goes
Defines CLOSE within the required DECLARE, OPEN, FETCH, and CLOSE order, but defers deallocation differences among database systems.
Examples
Demonstrates CLOSE AllOrders after a loop that totals qualifying book quantities by order.
What it assumes
Assumes cursor terminology while establishing the four required operations and their order.
What you can do after
Operate/configure a cursor lifecycle by closing it after fetching and processing its result set.
How it connects
Connects cursor cleanup with DECLARE, OPEN, FETCH, loops, stored procedures, and database-specific cursor deallocation.

Also explained in

Compare how 4 books explain close →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.