使用触发器做简单编程

有两张表(商品表和订单表,结构如下)

CREATE TABLE goods (
  gid int(11) DEFAULT NULL,
  name varchar(20) DEFAULT NULL,
  num smallint(6) DEFAULT NULL
);


CREATE TABLE ord (
  oid int(11) DEFAULT NULL,
  gid int(11) DEFAULT NULL,
  much smallint(6) DEFAULT NULL
);

插入数据:
INSERT INTO goods VALUES ('1','cat','32'), ('2','dog','65'), ('3','pig','21');

 业务场景如下:

客户如果买的东西超过了库存(goods表的num字段),如何预防,能否在购买量(插入ord表的much字段)>库存量(goods表的num字段)时,把much自动改为num

使用触发器:

create trigger t
before
insert
on ord
for each row

begin

declare
rnum int;

select num into rnum from goods where gid = new.gid;

if new.much > rnum then
	set new.much = rnum;
end if;

update goods set num = num - new.much where gid=new.gid;
end

  

 

转载于:https://www.cnblogs.com/lzxl/p/4116068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值