从 plpgSQL 触发到 MySQL

Trigger from plpgSQL to MySQL

我对触发器有疑问。 我已经在 plpgSQL 中为 PostgreSQL 创建了一个函数,但是,现在我需要在 MySQL 中执行此操作。我几乎尝试了一切,但我不知道该怎么做。有人知道该怎么做并帮助我吗?

这是 plpgSQL 中的代码:

CREATE OR REPLACE FUNCTION provjera_rezultata() RETURNS TRIGGER AS $
    DECLARE
    neodigrane_utakmice INT;

    BEGIN
    SELECT COUNT(*) INTO neodigrane_utakmice
    FROM utakmice AS u
        JOIN momcadi AS m1
            ON m1.momcad_ID = u.momcad_a
        JOIN momcadi AS m2
            ON m2.momcad_ID = u.momcad_b
    WHERE rezultat IS NULL;

    IF neodigrane_utakmice > 0 THEN
        RAISE NOTICE 'Broj utakmica bez rezultata je %', neodigrane_utakmice;
    END IF;

    RETURN NEW;
    END;
$ LANGUAGE plpgsql;

此外,我不知道在 MySQL 中为 "RAISE NOTICE" 从 PostgreSQL 使用什么。

我这样做了,但出现错误:(

DELIMITER $

CREATE TRIGGER provjera_rezultata
    AFTER INSERT ON utakmice FOR EACH ROW
    DECLARE broj INTEGER;

BEGIN
    SELECT COUNT(*) INTO broj
    FROM utakmice AS u
        JOIN momcadi AS m1
            ON m1.momcad_ID = u.momcad_a
        JOIN momcadi AS m2
            ON m2.momcad_ID = u.momcad_b
    WHERE rezultat IS NULL;

    IF broj > 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Postoje utakmice bez konacnog rezultata!';
    END IF;
END $

您的代码的内部部分可以基本保持不变。

触发器是使用 CREATE TRIGGER 创建的。

MySQL 中的通知称为 signals。你做

SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An error occurred'; 

在 MySQL 中,您在 begin-end 内声明变量。这段代码没有给我语法错误:

# test tables
CREATE TABLE utakmice(
    momcad_a INT,
    momcad_b INT,
    rezultat INT,
    PRIMARY KEY (momcad_a, momcad_b)
);
CREATE TABLE momcadi(
    momcad_ID INT AUTO_INCREMENT PRIMARY KEY
);


DELIMITER $$
CREATE TRIGGER provjera_rezultata
    AFTER INSERT ON utakmice FOR EACH ROW
BEGIN
    DECLARE broj INTEGER;
    SELECT COUNT(*) INTO broj
    FROM utakmice AS u
        JOIN momcadi AS m1
            ON m1.momcad_ID = u.momcad_a
        JOIN momcadi AS m2
            ON m2.momcad_ID = u.momcad_b
    WHERE rezultat IS NULL;

    IF broj > 0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Postoje utakmice bez konacnog rezultata!';
    END IF;
END $$

我知道这个 post 很旧,但我不知何故来到这里,它缺少答案。对于以后的问题,此答案可能会有所帮助。