创建表并导入数据;
mysql> use mydb16_trigger;
Database changed
mysql> create table goods(
-> gid char(8) primary key,
-> name varchar(10),
-> price decimal(8,2),
-> num int
-> );
Query OK, 0 rows affected (0.07 sec)
mysql> create table orders(
-> oid int primary key auto_increment,
-> gid char(10) not null,
-> name varchar(10),
-> price decimal(8,2),
-> onum int,
-> otime date
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into goods values('A0001','橡皮',2.5,100),('B0001','小楷本',2.8,210),('C0001', '铅笔',1.2,120),('D0001','计算器',28,20);
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
创建触发器:订单表中增加订单数量时,商品表商品数量同步减少对应的商品订单数量;
mysql> delimiter //
mysql> create trigger before_order_insert
-> before insert on orders
-> for each row
-> begin
-> update goods
-> set num =num - new.onum
-> where gid = new.gid;
-> end //
Query OK, 0 rows affected (0.05 sec)
mysql> delimiter ;
mysql> insert into orders (gid, name, price, onum, otime) values ('A0001', '橡皮', 2.5, 10, '2025-02-09');
Query OK, 0 rows affected (0.04 sec)
创建触发器:客户取消订单,恢复商品对应商品的数量;
mysql> delimiter //
mysql> create trigger after_order_delete
-> after delete on orders
-> for each row
-> begin
-> update goods
-> set num = num + old.onum
-> where gid = old.gid;
-> end //
Query OK, 0 rows affected (0.04 sec)
mysql> delimiter ;
mysql> delete from orders where oid = 1;
Query OK, 0 rows affected (0.04 sec)
创建触发器:客户修改订单,商品对应商品数量同步更新;
mysql> delimiter //
mysql> create trigger after_order_update
-> after update on orders
-> for each row
-> begin
-> update goods
-> set num = num - new.onum + old.onum
-> where gid = new.gid;
-> end //
Query OK, 0 rows affected (0.04 sec)
mysql> delimiter ;
mysql> update orders set onum = 5 where oid = 1;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
创建提取emp_new表所有员工姓名和工资的存储过程s1
mysql> use mydb7_openlab;
Database changed
mysql> delimiter //
mysql> create procedure s1()
-> begin
-> select 员工姓名, 工资
-> from emp_new;
-> end //
Query OK, 0 rows affected (0.04 sec)
创建存储过程s2,实现输入员工姓名后返回员工的年龄
mysql> delimiter //
mysql> create procedure s2(in emp_name varchar(50), out emp_age int)
-> begin
-> select 年龄 into emp_age
-> from emp_new
-> where 员工姓名 = emp_name;
-> end //
Query OK, 0 rows affected (0.04 sec)
创建一个存储过程s3,有2个参数,传入部门号,返回该部门的平均工资
mysql> delimiter //
mysql> create procedure s3(in dept_no int, out avg_salary decimal(10,2))
-> begin
-> select avg(工资) into avg_salary
-> from emp_new
-> where 部门号 = dept_no;
-> end //
Query OK, 0 rows affected (0.04 sec)