在触发器中使用变量

时间:2013-07-22 13:36:35

标签: mysql

我正在测试我的触发器并且它运行良好除了我似乎无法看到我的变量看起来不像他们应该的那样。

例如

DELIMITER //
CREATE TRIGGER lestrigger
    AFTER INSERT ON examinations
   FOR EACH ROW
  BEGIN
    DECLARE the_last_inserted_id INT ;
    DECLARE the_class_id INT;
    DECLARE the_year_id INT;

    SET the_last_inserted_id = LAST_INSERT_ID();
    SET the_class_id = (select examination_class_id from examinations where examination_id = 1);
    SET the_year_id = (select examination_class_id from examinations where examination_id = 1);

insert into examination_data (ed_cs_id,ed_examination_id)  select cs_id,@the_last_insert_id from class_students where cs_class_id = 1 AND cs_year_id = 1;

END //
DELIMITER ;

在这一行

insert into examination_data (ed_cs_id,ed_examination_id)  select cs_id,the_last_insert_id from class_students where cs_class_id = 1 AND cs_year_id = 1;

the_last_insert_id被视为专栏

当我尝试这个时,@the_last_insert_id,它不被视为一个列,但它也不起作用。我没有尝试过其余的变量。

我将如何定义和使用此the_last_inserted_id = LAST_INSERT_ID();

1 个答案:

答案 0 :(得分:0)

您可以设置

Select STH into the_last_inserted_id from TBL limit 1;

insert into examination_data (ed_cs_id,ed_examination_id)
select cs_id,the_last_insert_id 
from class_students
where cs_class_id = 1 AND cs_year_id = 1;

编辑: @ - 你正在使用而没有声明,只是设置

Select STH into @new_id from TBL limit 1;

然后

insert into examination_data (ed_cs_id,ed_examination_id)
select cs_id,@the_last_insert_id
from class_students
where cs_class_id = 1 AND cs_year_id = 1;