MySQL触发器获取文本变量



假设我们有两个表。

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

我们可以为"This user inserted This item"设置以下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";,此时触发器无法接受该变量。

你知道为什么只传递整数变量吗?

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

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)

最新更新