每个存储程序都包含一个由 SQL 语句组成的主体。该语句可以是由多个语句通过分号(;)分隔组成的复合语句。例如,下面的存储过程具有由一个 BEGIN ...
END 块组成的主体,该块包含一个 SET 语句和一个 REPEAT 循环,循环内部又包含另一个 SET 语句:Each stored program contains a body that consists of an SQL
statement. This statement may be a compound statement made up of
several statements separated by semicolon (;)
characters. For example, the following stored procedure has a body
made up of a BEGIN ...
END block that contains a
SET
statement and a REPEAT loop that
itself contains another
SET
statement:
CREATE PROCEDURE dorepeat(p1 INT) BEGIN SET @x = 0; REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT; END;
如果你使用mysql 客户端程序来定义包含分号字符的存储程序,会出现一个问题。默认情况下,mysql 会将分号识别为语句分隔符,因此你必须临时重新定义分隔符,使 mysql 将整个存储程序定义传递给服务器。If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
要重新定义 mysql 分隔符,请使用 delimiter 命令。以下示例展示了如何对刚才显示的 dorepeat() 存储过程执行此操作。分隔符被更改为 //,以便将整个定义作为单条语句传递给服务器,然后在调用存储过程之前恢复为 ;。这使得存储过程体中使用的 ; 分隔符可以传递给服务器,而不会被 mysql 本身解释。To redefine the mysql delimiter, use the
delimiter command. The following example shows
how to do this for the dorepeat() procedure
just shown. The delimiter is changed to // to
enable the entire definition to be passed to the server as a
single statement, and then restored to ; before
invoking the procedure. This enables the ;
delimiter used in the procedure body to be passed through to the
server rather than being interpreted by mysql
itself.
mysql>delimiter //mysql>CREATE PROCEDURE dorepeat(p1 INT)->BEGIN->SET @x = 0;->REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;->END->//Query OK, 0 rows affected (0.00 sec) mysql>delimiter ;mysql>CALL dorepeat(1000);Query OK, 0 rows affected (0.00 sec) mysql>SELECT @x;+------+ | @x | +------+ | 1001 | +------+ 1 row in set (0.00 sec)
您可以将分隔符重新定义为除 // 以外的字符串,分隔符可以由单个字符或多个字符组成。您应避免使用反斜杠 (\) 字符,因为它是 MySQL 的转义字符。You can redefine the delimiter to a string other than
//, and the delimiter can consist of a single
character or multiple characters. You should avoid the use of the
backslash (\) character because that is the
escape character for MySQL.
下面是一个示例函数,该函数接受一个参数,使用 SQL 函数执行操作,并返回结果。在这种情况下,不需要使用 delimiter,因为函数定义中没有内部的 ; 语句分隔符:The following is an example of a function that takes a parameter,
performs an operation using an SQL function, and returns the
result. In this case, it is unnecessary to use
delimiter because the function definition
contains no internal ; statement delimiters:
mysql>CREATE FUNCTION hello (s CHAR(20))mysql>RETURNS CHAR(50) DETERMINISTIC->RETURN CONCAT('Hello, ',s,'!');Query OK, 0 rows affected (0.00 sec) mysql>SELECT hello('world');+----------------+ | hello('world') | +----------------+ | Hello, world! | +----------------+ 1 row in set (0.00 sec)