Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
Applies to:
Databricks Runtime 18.1 and above
Opens a cursor and executes its query, positioning it before the first row.
The OPEN statement executes the query defined in the DECLARE CURSOR declaration, binding any parameter markers if specified. Once opened, the cursor can be used with FETCH to retrieve rows.
This statement may only be used within a compound statement.
Note
When opening the cursor, semantic errors such as TABLE_OR_VIEW_NOT_FOUND or COLUMN_NOT_FOUND_IN_TABLE are raised if present. Opening the cursor also starts execution of the query, which may raise runtime errors such as DIVIDE_BY_ZERO depending on how much of the query executes.
Syntax
OPEN cursor_name [ USING { constant_expr [ AS param_name ] } [, ...] ]
Parameters
-
The name of a declared cursor. The cursor can be optionally qualified with a compound statement label to reference a cursor from an outer scope (e.g.,
outer_label.my_cursor). USING { constant_expr [ AS param_name ] } [, ...]Optional clause to bind values to parameter markers in the cursor query.
- constant_expr: A constant expression (literal or variable) to bind to a parameter marker. The expression must be castable to the type expected by the query.
- AS param_name: Optional. For named parameter markers (
:param_name), this specifies which parameter to bind. If not specified for unnamed parameter markers (?), parameters are bound by position.
Notes
Parameter binding behavior matches EXECUTE IMMEDIATE:
- All parameter markers in the query must be bound.
- For named parameter markers (
:name), theAS param_nameclause specifies the binding. - For unnamed parameter markers (
?), expressions are bound in the order specified.
If the cursor's query raises an error during execution (see Error conditions), the cursor remains in a closed state. Opening a cursor that is not in scope raises CURSOR_NOT_FOUND. Opening a cursor that is already open raises CURSOR_ALREADY_OPEN.
Examples
-- Open a simple cursor without parameters
> BEGIN
DECLARE total INT;
DECLARE my_cursor CURSOR FOR SELECT sum(id) FROM range(10);
OPEN my_cursor;
FETCH my_cursor INTO total;
VALUES (total);
CLOSE my_cursor;
END;
45
-- Open cursor with positional parameters
> BEGIN
DECLARE total INT;
DECLARE param_cursor CURSOR FOR
SELECT sum(id) FROM range(100) WHERE id BETWEEN ? AND ?;
OPEN param_cursor USING 10, 20;
FETCH param_cursor INTO total;
VALUES (total);
CLOSE param_cursor;
END;
165
-- Open cursor with named parameters
> BEGIN
DECLARE min_val INT;
DECLARE named_cursor CURSOR FOR
SELECT min(id) FROM range(100) WHERE id >= :threshold;
OPEN named_cursor USING 25 AS threshold;
FETCH named_cursor INTO min_val;
VALUES (min_val);
CLOSE named_cursor;
END;
25