[sql] view plain copy
CREATE TRIGGER `tg_order_create` AFTER INSERT ON `tp_order` FOR EACH ROW BEGIN
DECLARE msg varchar(200)
/*冻结金额*/
IF 2=NEW.condition THEN
UPDATE `tp_user` SET `frozen_amount`=`frozen_amount`+NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` >NEW.amount
IF ROW_COUNT() <>1 THEN
set msg = "用户余额不足以完成支付."
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg
END IF
/*扣除金额*/
ELSEIF 3=NEW.condition THEN
UPDATE `tp_user` SET `amount`=`amount`-NEW.amount WHERE `id`=NEW.uid AND `amount`-`frozen_amount` >NEW.amount
/*如果余额不足,产生一个错误*/
IF ROW_COUNT() <>1 THEN
set msg = "用户余额不足以完成支付."
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg
END IF
END IF
END
这里这条触发器的功能是库存 *** 作,当库存足够的时候 减少库存,否则 抛出一个异常并报告商品库存不足:
[sql] view plain copy
CREATE TRIGGER `TG_order_detail_dec_stock` BEFORE INSERT ON `tp_order_detail` FOR EACH ROW BEGIN
DECLARE msg VARCHAR(200)
UPDATE `tp_stock` SET `num`=`num`-NEW.num WHERE `goods_id`=NEW.goods_id AND `mid`=NEW.mid AND `num`>=NEW.num
IF ROW_COUNT() <>1 THEN
SELECT CONCAT(`name`, ' 库存不足.') INTO msg FROM `tp_goods` WHERE `id`=NEW.goods_id
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg
END IF
END
在PHP端的处理(注:使用ThinkPHP框架):
[php] view plain copy
//前面省略若干行....
try {
if (false === ($order_pk = $tbl_order->add($order))) {
$tbl->rollback()
echo json_encode(array('success' =>-1, 'message' =>"创建订单失败!."), JSON_UNESCAPED_UNICODE)
return
}
}catch (\PDOException $e){
$errInfo=$e->errorInfo[2]
$tbl->rollback()
echo json_encode(array('success' =>-1, 'message' =>"创建订单失败!,{$errInfo}"), JSON_UNESCAPED_UNICODE)
return
}
//后面省略若干行....
你一个触发器当 insert into t20130406 表的时候, 触发。
触发的时候, 干的事情, 是 insert into t20130406 ...
这样不是递归了么?
如果你仅仅是想, 触发的时候, 干的事情,是把 name1 列的数值, 设置为 dd
那是很简单的。
SET new. name1 = 'dd'
就可以了。
下面是一个例子:
mysql>DELIMITER //
mysql>CREATE TRIGGER BeforeInsertTest
-> BEFORE INSERT ON test_trigger_table
->FOR EACH ROW
->BEGIN
-> SET new.val = '100'
->END
->//
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql>INSERT INTO test_trigger_table(id, name) VALUES (1, 'ABC')
->//
Query OK, 1 row affected (0.03 sec)
mysql>select * from test_trigger_table
->//
+------+------+------+
| id | name | val |
+------+------+------+
|1 | ABC | 100 |
+------+------+------+
1 row in set (0.00 sec)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)