gpt4 book ai didi

Mysql 'statement level' 触发器...你可以用两个技巧来做到这一点

转载 作者:行者123 更新时间:2023-11-29 18:52:58 28 4
gpt4 key购买 nike

我搜索了很多次,寻找任何技巧或解决方法来在 MySQL 中像 Oracle 那样制作“语句级”触发器,但我没有找到。所以我想出了这个技巧,它对我有用,希望它可以帮助任何人

请参阅下面我的回答。

最佳答案

假设我们想要插入多行,并且想要一次性执行某件事,但我们无法避免 MySQL 触发器中的“FOR EACH ROW”

`insert to table1 (sname,age) VALUES ('mariam',5),('jojo',3),('ahmed',29)`
  • 首先创建一个包含两列的表 statementidstable(ID,statementid)
  • 其次,您必须使用软件为您的账单准备一个唯一 ID

  • 假设是“123456”。

    将您的声明更改为

    INSERT INTO table1 (sname,age,uniqueid) VALUES ('mariam',5,123456),('jojo',3,123456),('ahmed',29,123456)

        CREATE TRIGGER
    table1_after_insert
    AFTER INSERT
    ON
    table1
    FOR EACH ROW
    BEGIN
    DECLARE isfired tinyint(1);
    SELECT COUNT(statementid) INTO isfired from statementidstable where statementid=NEW.uniqeid LIMIT 1;
    IF isfired = 0 THEN
    '''DO WHAT YOU WANT HERE because this is the first time for this statement id
    '''then insert the statementid to statementidstable
    INSERT INTO statementidstable (statementid) VALUES (NEW.uniqeid)
    ELSE
    '''Nothing will happen becaue you already have the statement id in statementidstable
    END IF;
    END;

    完成后从statementidstable中删除statementid(用您的软件处理)

** 另一个技巧,你可以做到这一点,不需要statementid,而且你的触发器可以在仅插入第一行后触发一次,或者在仅插入最后一行或两者都插入后触发一次

  • 在这个技巧中,你必须像这样准备你的陈述

      `insert to table1 (sname,age,rowid) VALUES ('mariam',5,1),('jojo',3,0),('dodo',3,0),('ahmed',29,-1)`

第一行有 rowid=1 (与任何其他行不同)使您的触发器知道它将在插入第一行后触发一次。

最后一行有 rowid=-1 (与任何其他行不同)让您的触发器知道它会在插入最后一行后触发一次。

其他行的 rowid=0 或 (1,-1) 之外的任何其他值

        CREATE TRIGGER
table1_after_insert
AFTER INSERT
ON
table1
FOR EACH ROW
BEGIN
IF rowid = 1 THEN
'''DO WHAT YOU WANT HERE after inserting first row only
ELSEIF rowid = -1
'''DO WHAT YOU WANT HERE after inserting last row only
ELSE
'''NOTHING WILL HAPPEN
END IF;
END;
  • 每个技巧都有其自己的好处...请注意,第一个技巧可以处理“插入语句”和“更新语句”
  • 我仍在处理“删除语句”

关于Mysql 'statement level' 触发器...你可以用两个技巧来做到这一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297014/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com