liveBook · Manning

Open

As explained in Learn SQL in a Month of Lunches

OPEN is a cursor operation that executes or activates the cursor's query and makes its result available for row retrieval.

OPEN activates a declared cursor. It executes the cursor’s SELECT query, stores the resulting data set in server memory, and prepares it for row-by-row retrieval with FETCH. section 22.2.1

Use OPEN as the second step in the cursor sequence:

Opening AllOrders

After declaring AllOrders for SELECT OrderID FROM orderheader, OPEN AllOrders executes that query. A LOOP can then FETCH each OrderID, process it, and eventually CLOSE the cursor. 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 ;

This complete procedure places OPEN between cursor declaration and the FETCH loop, then closes the cursor after processing every order. section 22.2.2

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains query execution, server-memory storage, ordering, and use before FETCH, without detailing cursor internals beyond storage.
Examples
Demonstrates OPEN AllOrders inside a MySQL procedure that totals titles sold at list price.
What it assumes
Assumes familiarity with cursor declaration and teaches OPEN as part of the DECLARE–OPEN–FETCH–CLOSE sequence.
What you can do after
Operate a cursor by opening its declared query before entering a FETCH loop.
How it connects
Connects OPEN with cursors, SELECT queries, DECLARE, FETCH, CLOSE, loops, stored procedures, and server memory.

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.