2013-07-22 27 views
0

我測試了我的觸發器,它運作良好,除了我似乎無法看到我的變量似乎不應該像他們應該工作。使用觸發器內的變量

例如

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

'SELECT LAST_INSERT_ID()INTO your_variable_name'或'SET your_variable_name = SELECT LAST_INSERT_ID();'。除了調用'LAST_INSERT_ID()'時,您對所有變量都使用'select'語句。 –

回答

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;