mysql触发器take text变量

avwztpqn  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(598)

假设我们有两张table。
第一个表是项目- id, title .
第二张table是历史- id, title, action, user .
“this user inserted this item”的插入后触发器如下:

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"; -在这一刻,触发器无法获取该变量。
你知道为什么只传递整数变量吗?

zzwlnbp8

zzwlnbp81#

好消息你的扳机没问题,这是证据

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)

相关问题