Mysql

如何在 mysql 腳本中轉義單引號?

  • July 29, 2021

我需要通過 mysql 腳本創建觸發器

CREATE TRIGGER sync_new_oauth_sessions
   AFTER INSERT
   ON oauth_sessions FOR EACH ROW
BEGIN
   SET @s = 'INSERT INTO oauth_sessions_new(id, client_id, owner_type, owner_id, owner_id_new) VALUES (?, ?, ?, ?, CAST(NULLIF(?,'''') AS UNSIGNED))';
   -- INSERT INTO oauth_sessions_new(id, client_id, owner_type, owner_id, owner_id_new) VALUES (NEW.id, NEW.client_id, NEW.owner_type, NEW.owner_id, CAST(NULLIF(NEW.owner_id,'') AS UNSIGNED));
   PREPARE stmt2 FROM @s;
   SET @sid = NEW.id;
   SET @s_client_id = NEW.client_id;
   SET @s_owner_type = NEW.owner_type;
   SET @s_owner_id = NEW.owner_id;
   SET @s_owner_id_new = NEW.owner_id;
   EXECUTE stmt2 USING @sid, @s_client_id, @s_owner_type, @s_owner_id, @s_owner_id_new;
END

這是腳本的內容。我越來越: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

我不明白我做錯了什麼。如果我這樣做\'\'了,我也會遇到同樣的問題。

謝謝

正確的錯誤資訊是

Error Code: 1336. Dynamic SQL is not allowed in stored function or trigger

SQL 準備語句(PREPARE、EXECUTE、DEALLOCATE PREPARE)可用於儲存過程,但不能用於儲存函式或觸發器。因此,儲存函式和触發器不能使用動態 SQL(您將語句構造為字元串然後執行它們)。

https://dev.mysql.com/doc/refman/8.0/en/stored-program-restrictions.html#stored-routines-trigger-restrictions

採用

DELIMITER //
CREATE TRIGGER sync_new_oauth_sessions
   AFTER INSERT
   ON oauth_sessions FOR EACH ROW
BEGIN

   INSERT INTO oauth_sessions_new(id, client_id, owner_type, owner_id, owner_id_new) VALUES (QUOTE(NEW.id), QUOTE(NEW.client_id), QUOTE(NEW.owner_type), QUOTE(NEW.owner_id), CAST(NULLIF(NEW.owner_id,'') AS UNSIGNED));
END
//

引用自:https://dba.stackexchange.com/questions/297365