Detailed Explanation of MySQL-SQL Stored Functions and Triggers

♥️Author : Xiao Liu at Station C

♥️Personal homepage:  Xiao Liu's homepage 

♥️Efforts may not necessarily pay off, but there will be gains! Come on! Work hard together for a better life!

♥️ Learn the operation and maintenance experience summed up in two years, and a full set of network experiment tutorials for Cisco simulators. Column: Cloud Computing Technology

♥️Xiao Liu private message can ask casually, as long as you know it, you will not be stingy, thank you CSDN for letting you and me meet!

Table of contents

MySQL

SQL

stored function

1 Introduction

2). Case

 trigger

introduce

 grammar

1). Create

2). View

3). Delete

the case

A. Insert data trigger

test:

B. Modify data trigger

test:

C. Delete data trigger

test:


MySQL

MySQL is a relational database management system, developed by the Swedish company MySQL AB, which is a product of Oracle. MySQL is one of the most popular relational database management systems. In terms of WEB applications, MySQL is one of the best RDBMS (Relational Database Management System, relational database management system) application software. MySQL is a relational database management system. Relational databases store data in different tables instead of putting all the data in one big warehouse, which increases speed and improves flexibility. The SQL language used by MySQL is the most commonly used standardized language for accessing databases. MySQL software adopts a dual authorization policy, which is divided into community edition and commercial edition. Due to its small size, fast speed, low overall cost of ownership, especially the open source feature, MySQL is generally chosen as the website for the development of small, medium and large websites. database.

SQL

Structured Query Language (Structured Query Language), referred to as SQL, is a special-purpose programming language. It is a database query and programming language for accessing data and querying, updating and managing relational database systems. Structured Query Language is a high-level non-procedural programming language that allows users to work on high-level data structures. It does not require the user to specify the data storage method, nor does it require the user to understand the specific data storage method, so different database systems with completely different underlying structures can use the same structured query language as the interface for data input and management. Structured query language statements can be nested, which makes it extremely flexible and powerful.

stored function

1). Introduction

A stored function is a stored procedure with a return value, and the parameters of the stored function can only be of type IN . The specific syntax is as follows:
CREATE FUNCTION 存储函数名称 ([ 参数列表 ])
RETURNS type [characteristic ...]
BEGIN
-- SQL语句
RETURN ...;
END ; 
characteristic description
DETERMINISTIC : the same input arguments always produce the same result
NO SQL : Does not contain SQL statements.
READS SQL DATA : Contains statements that read data, but not statements that write data.

2). Case

Calculate the value accumulated from 1 to n , where n is the value of the parameter passed in.
create function fun1(n int)
returns int deterministic
begin
declare total int default 0;
while n>0 do
set total := total + n;
set n := n - 1;
end while;
return total;
end;
select fun1(50);
In mysql8.0 version, binlog is enabled by default. Once enabled, mysql requires that when defining a stored procedure, you need to specify
characteristic feature, otherwise the following error will be reported:

 trigger

introduce

A trigger is a database object related to a table, which refers to a trigger before (BEFORE) or after (AFTER) insert /update/delete
Concurrently execute the set of SQL statements defined in the trigger. This feature of the trigger can assist the application to ensure data integrity, log records , data verification and other operations on the database side.
Use the aliases OLD and NEW to refer to the record content changed in the trigger, which is similar to other databases. Currently, triggers only support row-level triggers, not statement-level triggers.

 grammar

1). Create

CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON tbl_name FOR EACH ROW -- 行级触发器
BEGIN
trigger_stmt ;
END; 

2) .View

SHOW TRIGGERS ;

3). Delete

DROP TRIGGER [schema_name.]trigger_name ; -- 如果没有指定 schema_name,默认为当前数
据库 。

the case

Record the data change log of the tb_user table through the trigger , and insert the change log into the log table user_logs , including the increase ,
modify , delete ;
Table structure preparation :
-- 准备工作 : 日志表 user_logs

create table user_logs(

id int(11) not null auto_increment,

operation varchar(20) not null comment '操作类型, insert/update/delete',

operate_time datetime not null comment '操作时间',

operate_id int(11) not null comment '操作的ID',

operate_params varchar(500) comment '操作参数',

primary key(`id`)

)engine=innodb default charset=utf8;

A. Insert data trigger

create trigger tb_user_insert_trigger

after insert on tb_user for each row

begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params)

VALUES

(null, 'insert', now(), new.id, concat('插入的数据内容为:

id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ',

profession=', NEW.profession));

end;

test :

-- 查看

show triggers ;

-- 插入数据到tb_user

insert into tb_user(id, name, phone, email, profession, age, gender, status,

createtime) VALUES (26,'三皇子','18809091212','[email protected]','软件工

程',23,'1','1',now());
After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

B. Modify data trigger

create trigger tb_user_update_trigger

after update on tb_user for each row

begin

insert into user_logs(id, operation, operate_time, operate_id, operate_params)

VALUES

(null, 'update', now(), new.id,

concat('更新之前的数据: id=',old.id,',name=',old.name, ', phone=',

old.phone, ', email=', old.email, ', profession=', old.profession,

' | 更新之后的数据: id=',new.id,',name=',new.name, ', phone=',

NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));

end;

test :

-- 查看
show triggers ;
-- 更新
update tb_user set profession = '会计' where id = 23;
update tb_user set profession = '会计' where id <= 5;
After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

C. Delete data trigger

create trigger tb_user_delete_trigger

after delete on tb_user for each row

begin

insert into user_logs(id, operation, operate_time, operate_id, operate_params)

VALUES

(null, 'delete', now(), old.id,

concat('删除之前的数据: id=',old.id,',name=',old.name, ', phone=',

old.phone, ', email=', old.email, ', profession=', old.profession));

end;

test :

-- 查看
show triggers ;
-- 删除数据
delete from tb_user where id = 26; 
After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

♥️Following is the driving force for my creation

♥️Like, is the greatest recognition for me

♥️This is Xiaoliu, I am inspiring to do every article well, thank you everyone

Guess you like

Origin blog.csdn.net/lzl10211345/article/details/131357296