MYSQL触发器与更新

时间:2018-11-12 04:21:57

标签: mysql triggers

在同一张表已更新后,我试图构建一个触发器来通过引用另一张表来更新表字段。我尝试了以下代码,但每次尝试均会出现错误#1064。有人可以建议出什么问题了。 引用 尝试1。

BEGIN
UPDATE `incent` a INNER JOIN `inc_prog` b  
SET a.`earned` =
CASE WHEN a.incactualn < b.n1 THEN 0 
CASE WHEN a.incactualn  BETWEEN b.n1 AND b.m1 THEN b.arp1
CASE WHEN a.incactualn  BETWEEN b.n2 AND b.m2 THEN b.arp1+b.arp2
CASE WHEN a.incactualn  BETWEEN b.n3 AND b.m3 THEN b.arp1+b.arp2+b.arp3
CASE WHEN a.incactualn  BETWEEN b.n4 AND b.m4 THEN b.arp1+b.arp2+b.arp3+b.arp4
CASE WHEN a.incactualn  BETWEEN b.n5 AND b.m5 THEN b.arp1+b.arp2+b.arp3+b.arp4+b.arp5
END

===尝试1

尝试2

BEGIN
UPDATE
    a    
SET
a.earned = 
CASE WHEN a.incactualn < b.n1 THEN '0' 
CASE WHEN a.incactualn  BETWEEN b.n1 AND b.m1 THEN b.arp1
CASE WHEN a.incactualn  BETWEEN b.n2 AND b.m2 THEN b.arp1+b.arp2
CASE WHEN a.incactualn  BETWEEN b.n3 AND b.m3 THEN b.arp1+b.arp2+b.arp3
CASE WHEN a.incactualn  BETWEEN b.n4 AND b.m4 THEN b.arp1+b.arp2+b.arp3+b.arp4
CASE WHEN a.incactualn  BETWEEN b.n5 AND b.m5 THEN b.arp1+b.arp2+b.arp3+b.arp4+b.arp5

FROM
    incent a
INNER JOIN
    inc_prog b
ON
    a.Incent_name = b.incname && a.period = b.finyear
END

========尝试结束2

UNQUOTE

1 个答案:

答案 0 :(得分:0)

您只能在CASE表达式的开头放置单词CASE。只需删除第二份及后续副本。因此,您的第一个触发器变为:

BEGIN
    UPDATE `incent` a INNER JOIN `inc_prog` b  
    SET a.`earned` =
        CASE WHEN a.incactualn < b.n1 THEN 0 
             WHEN a.incactualn  BETWEEN b.n1 AND b.m1 THEN b.arp1
             WHEN a.incactualn  BETWEEN b.n2 AND b.m2 THEN b.arp1+b.arp2
             WHEN a.incactualn  BETWEEN b.n3 AND b.m3 THEN b.arp1+b.arp2+b.arp3
             WHEN a.incactualn  BETWEEN b.n4 AND b.m4 THEN b.arp1+b.arp2+b.arp3+b.arp4
             WHEN a.incactualn  BETWEEN b.n5 AND b.m5 THEN b.arp1+b.arp2+b.arp3+b.arp4+b.arp5
        END;
END

第二次尝试时,您缺少CASE表达式末尾的END以及子查询周围的(SELECT和):

BEGIN
    UPDATE a    
    SET a.earned = (SELECT
        CASE WHEN a.incactualn < b.n1 THEN '0' 
             WHEN a.incactualn  BETWEEN b.n1 AND b.m1 THEN b.arp1
             WHEN a.incactualn  BETWEEN b.n2 AND b.m2 THEN b.arp1+b.arp2
             WHEN a.incactualn  BETWEEN b.n3 AND b.m3 THEN b.arp1+b.arp2+b.arp3
             WHEN a.incactualn  BETWEEN b.n4 AND b.m4 THEN b.arp1+b.arp2+b.arp3+b.arp4
             WHEN a.incactualn  BETWEEN b.n5 AND b.m5 THEN b.arp1+b.arp2+b.arp3+b.arp4+b.arp5
        END
    FROM incent a
    INNER JOIN inc_prog b ON a.Incent_name = b.incname && a.period = b.finyear);
END