13.1.13 CREATE EVENT Statement语句

CREATE
    [DEFINER = user]
    EVENT
    [IF NOT EXISTS]
event_name
    ON SCHEDULE schedule
    [ON COMPLETION [NOT] PRESERVE]
    [ENABLE | DISABLE | DISABLE ON SLAVE]
    [COMMENT 'string']
    DO event_body;
schedule: {
    AT timestamp [+ INTERVAL interval] ...
  | EVERY interval
    [STARTS timestamp [+ INTERVAL interval] ...]
    [ENDS timestamp [+ INTERVAL interval] ...]
}
interval:
quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
              WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
              DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}

This statement creates and schedules a new event. 此语句创建并计划一个新事件。The event does not run unless the Event Scheduler is enabled. 除非启用了事件计划程序,否则事件不会运行。For information about checking Event Scheduler status and enabling it if necessary, see Section 25.4.2, “Event Scheduler Configuration”.有关检查事件计划程序状态并在必要时启用它的信息,请参阅第25.4.2节,“事件计划程序配置”

CREATE EVENT requires the EVENT privilege for the schema in which the event is to be created. CREATE EVENT要求要在其中创建事件的架构具有EVENT权限。If the DEFINER clause is present, the privileges required depend on the user value, as discussed in Section 25.6, “Stored Object Access Control”.如果存在DEFINER子句,则所需的权限取决于user值,如第25.6节,“存储对象访问控制”所述。

The minimum requirements for a valid CREATE EVENT statement are as follows:有效的CREATE EVENT语句的最低要求如下:

This is an example of a minimal CREATE EVENT statement:这是最小CREATE EVENT语句的示例:

CREATE EVENT myevent
    ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
    DO
      UPDATE myschema.mytable SET mycol = mycol + 1;

The previous statement creates an event named myevent. 前面的语句创建了一个名为myevent的事件。This event executes once—one hour following its creation—by running an SQL statement that increments the value of the myschema.mytable table's mycol column by 1.此事件在创建后一小时执行一次,方法是运行SQL语句,将myschema.mytable表的mycol列的值递增1。

The event_name must be a valid MySQL identifier with a maximum length of 64 characters. event_name必须是有效的MySQL标识符,最大长度为64个字符。Event names are not case-sensitive, so you cannot have two events named myevent and MyEvent in the same schema. 事件名称不区分大小写,因此在同一架构中不能有两个名为myeventMyEvent的事件。In general, the rules governing event names are the same as those for names of stored routines. 通常,控制事件名称的规则与存储例程名称的规则相同。See Section 9.2, “Schema Object Names”.请参阅第9.2节,“模式对象名称”

An event is associated with a schema. 事件与架构相关联。If no schema is indicated as part of event_name, the default (current) schema is assumed. 如果未将任何模式指示为event_name的一部分,则假定为默认(当前)模式。To create an event in a specific schema, qualify the event name with a schema using schema_name.event_name syntax.要在特定架构中创建事件,请使用schema_name.event_name语法使用架构限定事件名称。

The DEFINER clause specifies the MySQL account to be used when checking access privileges at event execution time. DEFINER子句指定在事件执行时检查访问权限时要使用的MySQL帐户。If the DEFINER clause is present, the user value should be a MySQL account specified as 'user_name'@'host_name', CURRENT_USER, or CURRENT_USER(). 如果存在DEFINER子句,则user值应为指定为'user_name'@'host_name'CURRENT_USERCURRENT_user()的MySQL帐户。The permitted user values depend on the privileges you hold, as discussed in Section 25.6, “Stored Object Access Control”. 允许的user值取决于您拥有的权限,如第25.6节,“存储对象访问控制”所述。Also see that section for additional information about event security.有关事件安全性的更多信息,请参阅该部分。

If the DEFINER clause is omitted, the default definer is the user who executes the CREATE EVENT statement. 如果省略DEFINER子句,则默认的DEFINER是执行CREATE EVENT语句的用户。This is the same as specifying DEFINER = CURRENT_USER explicitly.这与显式指定DEFINER=CURRENT_USER相同。

Within an event body, the CURRENT_USER function returns the account used to check privileges at event execution time, which is the DEFINER user. 在事件体中,CURRENT_USER函数返回用于在事件执行时检查权限的帐户,即DEFINER用户。For information about user auditing within events, see Section 6.2.22, “SQL-Based Account Activity Auditing”.有关事件中用户审核的信息,请参阅第6.2.22节,“基于SQL的帐户活动审核”

IF NOT EXISTS has the same meaning for CREATE EVENT as for CREATE TABLE: If an event named event_name already exists in the same schema, no action is taken, and no error results. IF NOT EXISTS对于CREATE EVENTCREATE TABLE具有相同的含义:如果名为event_name的事件已存在于同一架构中,则不会执行任何操作,也不会产生错误结果。(However, a warning is generated in such cases.)(但是,在这种情况下会生成警告。)

The ON SCHEDULE clause determines when, how often, and for how long the event_body defined for the event repeats. ON SCHEDULE子句确定为事件定义的event_body重复的时间、频率和持续时间。This clause takes one of two forms:本条款采用以下两种形式之一:

The ON SCHEDULE clause may use expressions involving built-in MySQL functions and user variables to obtain any of the timestamp or interval values which it contains. ON SCHEDULE子句可以使用包含内置MySQL函数和用户变量的表达式来获取它包含的任何时间戳或间隔值。You may not use stored functions or loadable functions in such expressions, nor may you use any table references; however, you may use SELECT FROM DUAL. 不得在此类表达式中使用存储函数或可加载函数,也不得使用任何表引用;但是,您可以使用SELECT FROM DUALThis is true for both CREATE EVENT and ALTER EVENT statements. CREATE EVENTALTER EVENT语句都是如此。References to stored functions, loadable functions, and tables in such cases are specifically not permitted, and fail with an error (see Bug #22830).在这种情况下,特别不允许引用存储函数、可加载函数和表,并且会因错误而失败(请参阅Bug#22830)。

Times in the ON SCHEDULE clause are interpreted using the current session time_zone value. 使用当前会话time_zone解释ON SCHEDULE子句中的时间。This becomes the event time zone; that is, the time zone that is used for event scheduling and is in effect within the event as it executes. 这成为事件时区;即,用于事件调度且在事件执行时在事件内有效的时区。These times are converted to UTC and stored along with the event time zone internally. 这些时间转换为UTC,并与事件时区一起存储在内部。This enables event execution to proceed as defined regardless of any subsequent changes to the server time zone or daylight saving time effects. 这使事件执行能够按照定义继续进行,而不管服务器时区或夏令时效果的任何后续更改。For additional information about representation of event times, see Section 25.4.4, “Event Metadata”. 有关事件时间表示的更多信息,请参阅第25.4.4节,“事件元数据”See also Section 13.7.7.18, “SHOW EVENTS Statement”, and Section 26.3.14, “The INFORMATION_SCHEMA EVENTS Table”.另请参阅第13.7.7.18节,“SHOW EVENTS语句”第26.3.14节,“INFORMATION_SCHEMA事件表”

Normally, once an event has expired, it is immediately dropped. 通常,一旦事件过期,它将立即被删除。You can override this behavior by specifying ON COMPLETION PRESERVE. 您可以通过指定ON COMPLETION PRESERVE来覆盖此行为。Using ON COMPLETION NOT PRESERVE merely makes the default nonpersistent behavior explicit.使用ON COMPLETION NOT PRESERVE只会使默认的非持久性行为显式化。

You can create an event but prevent it from being active using the DISABLE keyword. 您可以创建一个事件,但可以使用DISABLE关键字阻止它处于活动状态。Alternatively, you can use ENABLE to make explicit the default status, which is active. 或者,您可以使用ENABLE将默认状态显式设置为激活。This is most useful in conjunction with ALTER EVENT (see Section 13.1.3, “ALTER EVENT Statement”).这在与ALTER EVENT结合使用时最为有用(请参阅第13.1.3节,“ALTER EVENT语句”)。

A third value may also appear in place of ENABLE or DISABLE; DISABLE ON SLAVE is set for the status of an event on a replica to indicate that the event was created on the replication source server and replicated to the replica, but is not executed on the replica. 第三个值也可能出现在ENABLEDISABLE的位置;为复制副本上的事件状态设置了DISABLE ON SLAVE,以指示该事件是在复制源服务器上创建并复制到复制副本上的,但未在复制副本上执行。See Section 17.5.1.16, “Replication of Invoked Features”.请参阅第17.5.1.16节,“调用功能的复制”

You may supply a comment for an event using a COMMENT clause. 您可以使用comment子句为事件提供COMMENTcomment may be any string of up to 64 characters that you wish to use for describing the event. comment可以是您希望用于描述事件的最多64个字符的任何字符串。The comment text, being a string literal, must be surrounded by quotation marks.注释文本是字符串文字,必须用引号括起来。

The DO clause specifies an action carried by the event, and consists of an SQL statement. DO子句指定事件执行的操作,并由SQL语句组成。Nearly any valid MySQL statement that can be used in a stored routine can also be used as the action statement for a scheduled event. 几乎任何可以在存储例程中使用的有效MySQL语句都可以用作调度事件的操作语句。(See Section 25.8, “Restrictions on Stored Programs”.) (请参阅第25.8节,“存储程序的限制”。)For example, the following event e_hourly deletes all rows from the sessions table once per hour, where this table is part of the site_activity schema:例如,以下事件e_hourly每小时从sessions表中删除一次所有行,其中该表是site_activity架构的一部分:

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

MySQL stores the sql_mode system variable setting in effect when an event is created or altered, and always executes the event with this setting in force, regardless of the current server SQL mode when the event begins executing.MySQL存储在创建或更改事件时生效的sql_模式系统变量设置,并始终在该设置生效的情况下执行事件,而不管事件开始执行时的当前服务器sql模式如何。

A CREATE EVENT statement that contains an ALTER EVENT statement in its DO clause appears to succeed; however, when the server attempts to execute the resulting scheduled event, the execution fails with an error.DO子句中包含ALTER EVENT语句的CREATE EVENT语句似乎成功;但是,当服务器尝试执行生成的计划事件时,执行失败并出现错误。

Note注意

Statements such as SELECT or SHOW that merely return a result set have no effect when used in an event; the output from these is not sent to the MySQL Monitor, nor is it stored anywhere. 仅返回结果集的SELECTSHOW语句在事件中使用时无效;这些文件的输出不会发送到MySQL监视器,也不会存储在任何地方。However, you can use statements such as SELECT ... INTO and INSERT INTO ... SELECT that store a result. 但是,您可以使用SELECT ... INTOINSERT INTO ... SELECT用于存储结果的选项。(See the next example in this section for an instance of the latter.)(有关后者的实例,请参阅本节中的下一个示例。)

The schema to which an event belongs is the default schema for table references in the DO clause. 事件所属的模式是DO子句中表引用的默认模式。Any references to tables in other schemas must be qualified with the proper schema name.对其他架构中表的任何引用都必须使用正确的架构名称进行限定。

As with stored routines, you can use compound-statement syntax in the DO clause by using the BEGIN and END keywords, as shown here:与存储例程一样,您可以使用BEGINEND关键字在DO子句中使用复合语句语法,如下所示:

delimiter |

CREATE EVENT e_daily
    ON SCHEDULE
      EVERY 1 DAY
    COMMENT 'Saves total number of sessions then clears the table each day'
    DO
      BEGIN
        INSERT INTO site_activity.totals (time, total)
          SELECT CURRENT_TIMESTAMP, COUNT(*)
            FROM site_activity.sessions;
        DELETE FROM site_activity.sessions;
      END |

delimiter ;

This example uses the delimiter command to change the statement delimiter. 此示例使用delimiter命令更改语句分隔符。See Section 25.1, “Defining Stored Programs”.请参阅第25.1节,“定义存储程序”

More complex compound statements, such as those used in stored routines, are possible in an event. 在事件中可以使用更复杂的复合语句,如存储例程中使用的语句。This example uses local variables, an error handler, and a flow control construct:此示例使用局部变量、错误处理程序和流控制结构:

delimiter |

CREATE EVENT e
    ON SCHEDULE
      EVERY 5 SECOND
    DO
      BEGIN
        DECLARE v INTEGER;
        DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;

        SET v = 0;

        WHILE v < 5 DO
          INSERT INTO t1 VALUES (0);
          UPDATE t2 SET s1 = s1 + 1;
          SET v = v + 1;
        END WHILE;
    END |

delimiter ;

There is no way to pass parameters directly to or from events; however, it is possible to invoke a stored routine with parameters within an event:无法直接向事件传递参数或从事件传递参数;但是,可以使用事件中的参数调用存储的例程:

CREATE EVENT e_call_myproc
    ON SCHEDULE
      AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
    DO CALL myproc(5, 27);

If an event's definer has privileges sufficient to set global system variables (see Section 5.1.9.1, “System Variable Privileges”), the event can read and write global variables. 如果事件的定义人具有足够的权限设置全局系统变量(请参阅第5.1.9.1节,“系统变量权限”),则事件可以读取和写入全局变量。As granting such privileges entails a potential for abuse, extreme care must be taken in doing so.由于授予这种特权有可能被滥用,因此在这样做时必须格外小心。

Generally, any statements that are valid in stored routines may be used for action statements executed by events. 通常,在存储例程中有效的任何语句都可以用于事件执行的操作语句。For more information about statements permissible within stored routines, see Section 25.2.1, “Stored Routine Syntax”. 有关存储例程中允许的语句的更多信息,请参阅第25.2.1节,“存储例程语法”You can create an event as part of a stored routine, but an event cannot be created by another event.您可以创建一个事件作为存储例程的一部分,但另一个事件不能创建一个事件。