Mysql ON DUPLICATE KEY UPDATE里面的Triger语法错误

时间:2016-12-23 11:54:52

标签: mysql syntax triggers

谢谢三文鱼。 我有同样的工作。这是我第一次使用MySql的触发器。我现在已经使用MS Sql server多年的触发器了,我发现它在Mysql中很奇怪。它似乎永远不会开火或者没有足够快地捕捉事件。让我写下真实的代码并解释一下。

DROP trigger if exists sales_ins;
delimiter //
CREATE TRIGGER sales_ins
AFTER INSERT ON pos_items
FOR EACH ROW
BEGIN
DECLARE new_am INTEGER;
SET new_am = 0;
If NEW.item_class = 0 Then
    Select
          Sum(ifnull(pos_items.pos_quantity,0)) INTO new_am
        From
             pos_items Right Join pos_invoice On pos_items.inv_number = pos_invoice.inv_number And
            pos_items.branch_id = pos_invoice.branch_id
        Where
            pos_invoice.inv_void_cacel = 0 And pos_items.item_class = 0 And pos_items.item_code = NEW.item_code
        Group By
            pos_items.item_code
        Having
            Not pos_items.item_code Is Null;
    REPLACE INTO item_quantity VALUES (NEW.company_id, NEW.branch_id, NEW.item_code, 
        0, 0, 0,    new_am, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, now(), NEW.rowguid);
ElseIf NEW.item_class = 7 Then
    Select
          Sum(ifnull(pos_items.pos_quantity,0)) INTO new_am
        From
             pos_items Right Join pos_invoice On pos_items.inv_number = pos_invoice.inv_number And
            pos_items.branch_id = pos_invoice.branch_id
        Where
            pos_invoice.inv_void_cacel = 0 And pos_items.item_class = 7 And pos_items.item_code = NEW.item_code
        Group By
            pos_items.item_code
        Having
            Not pos_items.item_code Is Null;
    REPLACE INTO item_quantity VALUES (NEW.company_id, NEW.branch_id, NEW.item_code, 
        0, 0, 0, 0, new_am, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, now(), NEW.rowguid);
End If;
END //
delimiter ;

问题是,它没有更新。为清楚起见,我将解释代码。 一旦pos_items表在插入后触发(在使用插入之后因为我需要将此数量与总和相加),它将把所有交易总和作为销售数量并更新item_quantity item_sold_qty字段或者如果它是re​​turn,item_salesret_qty字段。

未发生的事情是更新的数量不准确。 错误的方式和位置,或者每个创建视图都创建了一个myisam表,这也是延迟执行。只是我不明白。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

DROP TRIGGER IF EXISTS sales_ins;
delimiter //
CREATE TRIGGER sales_ins
AFTER INSERT ON pos_items
FOR EACH ROW
BEGIN
INSERT INTO item_quantity (
    company_id,branch_id,item_Code,item_Pur_Qty,item_PurRet_Qty,item_Damaged,
    item_Sold_Qty,item_SalesRet_Qty,item_OtherSales_Ret,item_Stock_From,
    item_Stock_To,item_Stock_Adjust,rem_Sales,item_Transfered,item_Stores_Qty,
    item_MarRets,item_DelPur,item_Samples,item_Tailor,dateguid,rowguid)
VALUES (
    NEW.company_id, NEW.branch_id, NEW.item_code, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, now(), NEW.rowguid)
ON DUPLICATE KEY UPDATE
    item_Sold_Qty = 0, 
    dateguid = now();
END //
delimiter ;