mysql_stored routines (stored function stored procedure trigger event cursor)

Stored procedure

classification

Insert picture description here

Stored routine

Essentially, it also encapsulates some executable statements, but the way it is called is 显示调用. Stored routines can be divided into stored functions and stored procedures. The difference between the two is as follows:

Storage function Stored procedure
return statement must have You may have
Number of return values 1 piece >=1
Parameter Type in in (default) out inout
display Select during execution will not be displayed The select during execution will be displayed
transfer Can be called directly in expressions and SQL statements Can only use the CALL statement to display the call

Among them, the stored procedure does not need 返回值, but the stored function must have 返回值. In addition, all result sets generated by the stored procedure during the execution of the query statement will all be displayed to the client.

Storage function

  • definition

    CREATE FUNCTION 存储函数名称([参数名 数据类型]组成的参数列表) comment ‘函数的注释说明’ 
    RETURNS 返回值类型
    BEGIN
        函数体内容
        -- 函数体中,每条语句都要以分号;结尾
        -- 函数体内容可以包含:
        -- 1. SQL语句,如:
        -- 2. 变量定义(此时变量的定义用declare,不加@)和赋值
           DECLARE 变量名 数据类型 [DEFAULT 默认值];  -- 不声明默认值时,默认值为NULL 
           set 变量名 = 变量/;
        -- 3. 流程控制语句
           -- 3.1 条件语句
              if 布尔表达式 then
                 处理语句
              elseif 布尔表达式 then
                 处理语句
              else 
                 处理语句
              end if;
           -- 3.2 循环语句
              -- 方式1
              while 布尔表达式 do
                 循环语句
              end while;
              -- 方式2
              repeat
                 循环语句
              until 布尔表达式 end repeat;
              -- 方式3
              循环标记:loop
                 循环语句
                 leave 循环标记; -- leave语句一般和判断语句一起用,用来退出循环
              end loop 循环标记
        
    END
    

    example:

    create function avg_score(s varchar(100))
    return double
    begin
        declare c int default 1;
        set c = s;
    	return (select avg(score) from student_score where subject = s)
    end $
    
  • transfer

    The user-defined function is used in the same way as the system built-in function. Directly 函数名()to
    Insert picture description here

  • View

    -- 查看定义的函数有哪些
    SHOW FUNCTION STATUS [LIKE 需要匹配的函数名]
    -- 查看某个函数的具体定义
    SHOW CREATE FUNCTION 函数名
    
  • delete

    DROP FUNCTION 函数名
    

Stored procedure

  • definition

    CREATE PROCEDURE 存储过程名称([参数类型 参数名 数据类型]组成的参数列表)
    -- 存储过程的参数类型有三种:in out inout
    -- in:实参可为常量/变量;实参为变量时,只能向外赋值,不能被赋值(即in型参数的值不会被存储过程更改)
    -- out:实参只能是变量;实参不能向外赋值,只能被赋值
    -- inout:实参只能是变量;实参既可向外赋值,又可被赋值
    BEGIN
        需要执行的语句,可包含内容和存储函数是一样的。
    END    
    

    example:

    create procedure t1_operation(m1_value int, n1_value char(1))
    begin
    	select * from t1;
    	insert into t1(m1,n1) values(m1_value,n1_value);
    	select * from t1;
    end $
    
  • transfer

    call 存储过程([参数列表]);
    
  • View

    -- 查看定义的存储过程有哪些
    SHOW PROCEDURE STATUS [LIKE 需要匹配的函数名]
    -- 查看某个存储过程的详细定义
    SHOW CREATE PROCEDURE 存储过程名称
    
  • delete

    DROP PROCEDURE 存储过程名称
    

trigger

The function of the trigger is 自动地to 操作所涉及的记录perform the trigger operation (that is, implicitly called by the server ) before or after an operation (addition, deletion, modification) is performed on a certain table .

  • definition

    -- 竖线"|"分隔的语句表示必须在给定的选项中选取一个值
    CREATE TRIGGER 触发器名
    {BEFORE|AFTER}          
    {
         
         INSERT|DELETE|UPDATE}
    ON 表名
    FOR EACH ROW 
    BEGIN
        触发器操作
    END
    

    CREATE TRIGGER 触发器名

    The general naming rule for trigger names is: "b/a"+"i/d/u"+"_"+"table name", for example, bi_t1, which means that a before insert type trigger is set for table t1.

    BEFORE AFTER

    Insert picture description here

    INSERT DELETE UPDATE

    MySQL currently only supports setting triggers for three types of statements: INSERT, DELETE, and UPDATE.

    FOR EACH ROW

    Indicates that the trigger scope is增删改操作涉及的记录

    • For INSERT, the records affected by FOR EACH ROW are the new records we are going to insert.
    • For DELETE and UPDATE, the records affected by FOR EACH ROW are those records that meet the WHERE condition (if there is no WHERE condition in the statement, it means all records).

    BEGIN ... END

    Indicates the action that the trigger needs to perform. Among them 不能有输出结果集相关的语句,, such as select.

    In addition, the trigger uses "new"and "old"to indicate records that do not exist and already exist in the original table. among them,

    • For the trigger set by the INSERT statement, it NEWrepresents the record to be inserted and will not be used OLD.
    • For the trigger set by the DELETE statement, it OLDrepresents the record before the deletion and will not be used NEW.
    • For the trigger set by the UPDATE statement, it NEWrepresents the record after modification and the record OLDbefore modification.

    Example :

    create trigger bi_ti
    before insert on t1
    for each row
    begin
    	if new.m1<1 then
    		set new.m1 =1;
    	elseif new.m1>10 then
    		set new.m1 = 10;
    	end if;
    end $
    
  • transfer

    The trigger call is executed when the table is added, deleted, or modified 自动.

  • View

    -- 查看数据库中有哪些触发器
    show triggers
    -- 查看某个触发器的定义
    show create trigger 触发器名;
    
  • delete

    drop trigger 触发器名;
    

event

Events can be implemented, 自动地(that is, implicitly called by the server), 某个时间点or 某隔一段时间execute certain commands once.

  • definition

    CREATE EVENT 事件名
    ON SCHEDULE
    {AT 某个确定的时间点 | EVERY 期望的时间间隔 [STARTS datetime][END datetime]}
    DO
    BEGIN
        具体的语句
    END
    

    example:

    -- 指定某个时间点执行
    CREATE EVENT insert_t1
    ON SCHEDULE
    AT '2018-03-10 15:48:54'
    -- 也可以写成:AT DATE_ADD(NOW(), INTERVAL 2 DAY)
    DO
    BEGIN
        INSERT INTO t1(m1, n1) VALUES(6, 'f');
    END
    
    -- 指定某个时间间隔执行
    CREATE EVENT insert_t1
    ON SCHEDULE
    EVERY 1 HOUR STARTS '2018-03-10 15:48:54' ENDS '2018-03-12 15:48:54'
    -- 也可以写成:EVERY 1 HOUR 
    DO
    BEGIN
        INSERT INTO t1(m1, n1) VALUES(6, 'f');
    END
    
  • transfer

    The event will be automatically called by the server under the corresponding time setting.

    The automatic invocation of events needs to be turned on in the server:

    -- 启动mysql服务器时,开启事件监听
    event_scheduler = ON
    -- 开启mysql服务器后,通过设置mysql服务器的环境变量,开启事件监听
    set global event_scheduler = ON
    
  • View

    -- 查看数据库定义的事件
    SHOW EVENTS;
    -- 查看某个事件具体创建命令
    SHOW CREATE EVENT 事件名;
    
  • delete

    DROP EVENT 事件名;
    

cursor

Similar to an iterator, it is used for 标记result collection 正在访问的某一行记录. In the initial state, it marks the first record in the result set and automatically moves to the next record after each use.

When a cursor can be used in a stored function and a stored procedure, the creation, opening, calling, and closing of the cursor are all completed in the stored function and stored procedure.

  • create

    DECLARE 游标名称 CURSOR FOR 查询语句; -- 注意,创建游标的语句必须放在变量声明的后面
    
  • turn on

    Opening a cursor means to execute a query statement and associate the created cursor with the result set obtained by the query statement.

    open 游标名称;
    
  • transfer

    Assign the value of each column of the record corresponding to the specified cursor to the following INTOvariables in turn. After assignment, 自动移动到下一条记录the position of the cursor .

    -- fetch语句一般用在循环语句中
    FETCH 游标名 INTO 变量1, 变量2, ... 变量n
    
  • shut down

    Closing the cursor means that the memory occupied by the cursor will be released.

    close 游标名称;
    
  • example

    CREATE PROCEDURE cursor_demo()
    BEGIN
        -- 声明变量
        DECLARE m_value INT;
        DECLARE n_value CHAR(1);
        DECLARE not_done INT DEFAULT 1;
    
        -- 声明游标
        DECLARE t1_record_cursor CURSOR FOR SELECT m1, n1 FROM t1; 
    
        -- 在游标遍历完记录的时候将变量 not_done 的值设置为 0,并且继续执行后边的语句
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_done = 0;  
    
        -- 打开游标
        OPEN t1_record_cursor;
    
        WHILE not_done = 1 DO
            -- 使用游标
            FETCH t1_record_cursor INTO m_value, n_value;
            SELECT m_value, n_value, not_done;
        END WHILE;
    
        CLOSE t1_record_cursor;
    END
    

references

https://mp.weixin.qq.com/s?__biz=MzIxNTQ3NDMzMw==&mid=2247483968&idx=1&sn=08a4072e046cc7833b60cc9d66298ec8&scene=19#wechat_redirect storage program (2) Introduction to storage functions

https://mp.weixin.qq.com/s?__biz=MzIxNTQ3NDMzMw==&mid=2247483972&idx=1&sn=4b9cc8c88eea19fd726fc61738d7acea&scene=19#wechat_redirect stored procedure (3) Introduction to the stored procedure

https://mp.weixin.qq.com/s?__biz=MzIxNTQ3NDMzMw==&mid=2247483976&idx=1&sn=f39ffa2f4388f1f6b593bfeb1094c5a4&scene=19#wechat_redirect stored procedure (4) cursor introduction

https://mp.weixin.qq.com/s?__biz=MzIxNTQ3NDMzMw==&mid=2247483980&idx=1&sn=3a3811cf19fadf87f326ad71c3b6f20a&scene=19#wechat_redirect Store procedure (5) Introduction to triggers and events

https://www.cnblogs.com/aixinyiji/p/11038635.html Exception handling in MYSQL

Guess you like

Origin blog.csdn.net/u013617791/article/details/104854495