MySQL触发器检查数据-如何调用过程并引用“new”?

MySQL触发器检查数据-如何调用过程并引用“new”?,mysql,stored-procedures,triggers,Mysql,Stored Procedures,Triggers,对于MySQL,我希望使用插入前和更新前触发器来检查数据,类似于检查条件的工作方式。我可以很容易地编写代码,而且它可以工作,但是因为我需要两个触发器insert+update,并且检查代码是相同的,所以我想把它放到一个过程中。然而,似乎我不能在过程中仅在触发器中使用新的限定符。它也不能作为参数传递 有什么办法吗?我真的很讨厌在两个触发器中重复检查代码 太糟糕了,触发器语法不能类似于在插入或更新之前创建触发器t 更新:我编写了一个PHP函数来创建这两个触发器,而不需要两份检查代码。我仍然想知道是否

对于MySQL,我希望使用插入前和更新前触发器来检查数据,类似于检查条件的工作方式。我可以很容易地编写代码,而且它可以工作,但是因为我需要两个触发器insert+update,并且检查代码是相同的,所以我想把它放到一个过程中。然而,似乎我不能在过程中仅在触发器中使用新的限定符。它也不能作为参数传递

有什么办法吗?我真的很讨厌在两个触发器中重复检查代码

太糟糕了,触发器语法不能类似于在插入或更新之前创建触发器t

更新:我编写了一个PHP函数来创建这两个触发器,而不需要两份检查代码。我仍然想知道是否有一种纯粹的MySQL方法可以做到这一点,而不必重复检查代码

function add_trigger($table, $sql) {
    dbquery2("drop trigger if exists table_{$table}_trigger1");
    dbquery2("drop trigger if exists table_{$table}_trigger2");
    dbquery2("create trigger table_{$table}_trigger1 before insert on $table for each row begin $sql end");
    dbquery2("create trigger table_{$table}_trigger2 before update on $table for each row begin $sql end");
}
dbquery2是我自己的函数,它调用mysqli::query

更新2:鉴于SQL将由PHP生成,这里有一个改进的版本,它只使用一个过程。这些长得离谱的参数列表是由PHP根据信息_模式生成的,因此它们的长度和冗余并不重要

function add_trigger($table, $sql) {
    if ($result = dbquery2("select column_name, column_type from information_schema.columns where table_schema = 'cwadb_local' and table_name = '$table'")) {
        while ($row = $result->fetch_assoc()) {
            $cols .= ", new.{$row['column_name']}";
            $params .= ", {$row['column_name']} {$row['column_type']}";
        }
        $cols = substr($cols, 2); // remove extra ", " at front
        $params = substr($params, 2);
        $t1 = "create trigger table_{$table}_trigger1 before insert on $table for each row begin call check_table_{$table}($cols); end";
        $t2 = "create trigger table_{$table}_trigger2 before update on $table for each row begin call check_table_{$table}($cols); end";
        $proc = "create procedure check_table_{$table}($params) begin $sql end";
        dbquery2("drop procedure if exists check_table_{$table}"); // like mysqli::query, but throws exception on error
        dbquery2("drop trigger if exists table_{$table}_trigger1");
        dbquery2("drop trigger if exists table_{$table}_trigger2");
        dbquery2($t1);
        dbquery2($t2);
        dbquery2($proc);
        echo "<p>Success!";
    }
}

我正在编写一个PHP函数add_trigger,它将触发器添加到数据库中。它生成SQL代码来创建这两个触发器,然后执行它。这样,检查代码只有一个副本。