For the complete documentation index, see llms.txt. This page is also available as Markdown.

DECLARE CURSOR

Syntax

DECLARE cursor_name CURSOR [(cursor_formal_parameter[,...])] FOR {select_statement | prepared_statement_name}

cursor_formal_parameter:
    [IN] name type [collate clause]
DECLARE cursor_name CURSOR [(cursor_formal_parameter[,...])] FOR select_statement

cursor_formal_parameter:
    name type [collate clause]

Description

This statement declares a cursor. Multiple cursors may be declared in a stored program, but each cursor in a given block must have a unique name.

select_statement is not executed until the OPEN statement is executed. It is important to remember this if the query produces an error, or calls functions which have side effects.

A SELECT associated to a cursor can use variables, but the query itself cannot be a variable, and cannot be dynamically composed. The SELECT statement cannot have an INTO clause.

Starting with MariaDB 12.3, the query can also be a prepared statement name, which allows the query to be dynamically composed. The SELECT statement cannot have an INTO clause.

Cursors must be declared before HANDLERs, but after local variables and CONDITIONs.

The DECLARE CURSOR statement provides a cursor to a specified SELECT statement.

To declare a cursor variable type that can be connected with multiple queries at runtime (REF CURSOR), use DECLARE TYPE... IS REF CURSOR in Oracle mode. See DECLARE TYPE.

Dynamic Cursors

Starting with MariaDB 12.3, a cursor can be declared for a prepared statement. This allows the use of Dynamic SQL within stored routines. The cursor is bound to a prepared statement name, which must be defined using the PREPARE statement before the cursor is opened.

Parameters

Cursors can have parameters. This is a non-standard SQL extension. Cursor parameters can appear in any part of the DECLARE CURSOR select_statement where a stored procedure variable is allowed (select list, WHERE, HAVING, LIMIT , and so forth).

IN

The IN qualifier is supported in the cursor_formal_parameter part of the syntax.

The IN qualifier is not supported in the cursor_formal_parameter part of the syntax.

See Cursor Overview for an example.

See Also

This page is licensed: GPLv2, originally from fill_help_tables.sql

spinner

Last updated

Was this helpful?