首页 > 解决方案 > MySQL 触发器获取文本变量

问题描述

假设我们有两张桌子。

第一个表是项目- id, title
第二张表是历史- id, title, action, user

我们可以为“此用户插入此项目”设置以下 AFTER INSERT 触发器:

INSERT INTO history (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);

如果我想插入新项目,我可以这样做。

SET @phpUserId = 123;
INSERT INTO items (title) VALUES ('My best item');

在这种情况下,触发器完美地工作。

但问题是,当我将一些文本添加到变量中时——例如SET @phpUserId = "library123";——此时触发器无法获取该变量。

任何想法为什么只传递整数变量?

标签: mysqldatabasetriggers

解决方案


好消息,您的触发器没有问题,这是证据

drop table if exists i,h;
create table i(id int, title varchar(20));
create table h(id int, title varchar(20), action varchar(20), user varchar(30));

drop trigger if exists t;
delimiter $$
create trigger t after insert on i
for each row 
begin
    INSERT INTO h (title, action, user) VALUES (NEW.title, 'INSERT', @phpUserId);
end $$

delimiter ;

SET @phpUserId = 123;
INSERT INTO i (title) VALUES ('My best item');
SET @phpUserId = 'bob123';
INSERT INTO i (title) VALUES ('My worst item');

+------+---------------+--------+--------+
| id   | title         | action | user   |
+------+---------------+--------+--------+
| NULL | My best item  | INSERT | 123    |
| NULL | My worst item | INSERT | bob123 |
+------+---------------+--------+--------+
2 rows in set (0.00 sec)

推荐阅读