SQL reference (MySQL and MariaDB dialects)

CREATE PROCEDURE, CREATE FUNCTION, CALL and the stored program language

Stored procedures and functions: definitions, CALL, variables, flow control, cursors, handlers, SIGNAL and the limits of this version.

A stored routine is a named program kept in its database and run by the server (D87). A procedure is run with CALL and may return result sets and OUT values. A function is called inside a statement and returns one value. A call can produce several result sets in one answer; the front-end sends them with the "more results" status flag, in the text and the binary protocol.

Syntax#

SQL
CREATE [OR REPLACE] [DEFINER = account]
    PROCEDURE [IF NOT EXISTS] [db_name.]sp_name ([proc_parameter [, ...]])
    [characteristic] ... routine_body

CREATE [OR REPLACE] [DEFINER = account]
    FUNCTION [IF NOT EXISTS] [db_name.]sp_name ([func_parameter [, ...]])
    RETURNS type
    [characteristic] ... routine_body

proc_parameter:  [IN | OUT | INOUT] param_name type
func_parameter:  param_name type

characteristic:
    COMMENT 'string'
  | LANGUAGE SQL
  | [NOT] DETERMINISTIC
  | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
  | SQL SECURITY { DEFINER | INVOKER }

CALL [db_name.]sp_name [(expr [, expr] ...)]

DROP { PROCEDURE | FUNCTION } [IF EXISTS] [db_name.]sp_name

SHOW CREATE { PROCEDURE | FUNCTION } sp_name
SHOW { PROCEDURE | FUNCTION } STATUS [LIKE 'pattern' | WHERE expr]

The body is one statement or a compound statement:

SQL
[label:] BEGIN
    [DECLARE var_name [, ...] type [DEFAULT value];]
    [DECLARE condition_name CONDITION FOR { SQLSTATE [VALUE] 'xxxxx' | mysql_error_code };]
    [DECLARE cursor_name CURSOR FOR select_statement;]
    [DECLARE { CONTINUE | EXIT } HANDLER FOR condition_value [, ...] statement;]
    statement; ...
END [label]

condition_value:
    SQLEXCEPTION | SQLWARNING | NOT FOUND | SQLSTATE [VALUE] 'xxxxx' | mysql_error_code | condition_name

statement:
    SET var = expr [, var = expr] ...
  | IF cond THEN ... [ELSEIF cond THEN ...] [ELSE ...] END IF
  | CASE [expr] WHEN ... THEN ... [ELSE ...] END CASE
  | [label:] WHILE cond DO ... END WHILE [label]
  | [label:] REPEAT ... UNTIL cond END REPEAT [label]
  | [label:] LOOP ... END LOOP [label]
  | LEAVE label | ITERATE label
  | RETURN expr                                   -- functions
  | SELECT ... INTO var [, var] ...
  | OPEN cursor | FETCH cursor INTO var [, var] ... | CLOSE cursor
  | SIGNAL { SQLSTATE [VALUE] 'xxxxx' | condition_name } [SET item = value [, ...]]
  | RESIGNAL [...]
  | GET DIAGNOSTICS [CONDITION n] var = { MYSQL_ERRNO | MESSAGE_TEXT | ... } [, ...]
  | CALL sp_name (...)
  | any other statement, kept as text and run by the ordinary executor

Arguments#

NameMeaningDefault
IN, OUT, INOUTParameter mode. OUT and INOUT give their value to a user variable (or a local variable of a calling routine).IN
OR REPLACE, IF NOT EXISTSReplace an existing routine / do nothing if it exists.off
DEFINERStored and shown.the creating account
DETERMINISTIC, CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA, NO SQL, SQL SECURITY, COMMENTStored and shown (SHOW CREATE, information_schema.ROUTINES). They do not restrict what the body does.NOT DETERMINISTIC, CONTAINS SQL, DEFINER

Remarks#

  • Storage. A definition is one document in the hidden table __rdb_routines of its database (key p:name or f:name), read once and kept in a cache.
  • Parsing. The body is parsed when the routine is made (a body that does not parse is refused) and again each time it runs.
  • Running. The local variables in a statement's text are replaced by their values (not after a ., not before ( or ., not an alias, not a column list of INSERT, not the target of UPDATE ... SET); the ordinary parser and executor then run the text. Result sets of the statements go to the client. An error goes to the handlers of the block, then of the blocks around it. The default database is the routine's while it runs.
  • Recursion is refused unless max_sp_recursion_depth allows it. A call is stopped after 50 million statements and loop turns.
  • Functions are called in a statement; the calls are found in its text and run first, then replaced by their values. A call that is a whole select item keeps its text as the column name. The arguments of a function call must not use columns of the row (that is refused as unsupported).
  • DELIMITER is a client command (the mysql program), not a statement of the server. Drivers send the whole CREATE PROCEDURE text as one statement.
  • Differences between the dialects are those of MySQL and MariaDB (the output is identical to MySQL 9.7 and MariaDB 11.4 except the account host in DEFINER and the times; Raft DB's server time zone is UTC).
  • Privileges. EXECUTE and CREATE ROUTINE are known to GRANT but are not checked when creating or calling a routine in this version.

Not supported yet#

  • ALTER PROCEDURE, ALTER FUNCTION (error 1235).
  • SQL SECURITY INVOKER rights checks.
  • A function called with a column of the row as an argument.
  • Oracle-style packages and %TYPE.
  • Events (CREATE EVENT).

Examples#

Example (run with the client command DELIMITER //):

SQL
CREATE PROCEDURE p_sum(IN a INT, IN b INT, OUT s INT)
BEGIN
  SET s = a + b;
END//

CREATE PROCEDURE p_cursor()
BEGIN
  DECLARE done INT DEFAULT 0;
  DECLARE v INT;
  DECLARE s INT DEFAULT 0;
  DECLARE c CURSOR FOR SELECT n FROM t ORDER BY id;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
  OPEN c;
  rd: LOOP
    FETCH c INTO v;
    IF done = 1 THEN LEAVE rd; END IF;
    SET s = s + v;
  END LOOP;
  CLOSE c;
  SELECT s;
END//

CREATE PROCEDURE p_signal(IN v INT)
BEGIN
  IF v < 0 THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'negative not allowed', MYSQL_ERRNO = 5001;
  END IF;
  SELECT v;
END//

CREATE FUNCTION f_add(a INT, b INT) RETURNS INT DETERMINISTIC
BEGIN
  RETURN a + b;
END//

CALL p_sum(3, 4, @s);
SELECT @s;                         -- 7
SELECT f_add(2, 3);                -- 5
SHOW CREATE PROCEDURE p_sum;
DROP PROCEDURE IF EXISTS p_hello;

See also#