2013-07-21 40 views
0

我聲明我的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 = the_last_inserted_id; 
    SET the_year_id = select examination_class_year_id from examinations where examination_id = the_last_inserted_id; 

    insert into examination_data (ed_cs_id,ed_examination_id) select cs_id from class_students where cs_class_id = the_class_id AND cs_year_id = the_year_id,the_last_inserted_id; 

END 
    // 
DELIMITER ; 

一些變數,但我不斷收到此錯誤

/* SQL錯誤(1064)使用變量:您有一個錯誤在你的SQL語法中;檢查對應於你的MySQL服務器版本的權利 語法使用附近的 手冊「從考試 選擇examination_class_id其中examination_id = the_last_in」第10行*/

是我使用我的變量語法的方式對?。

+0

嘗試添加括號。 – Hidde

+0

http://stackoverflow.com/questions/12797424/selecting-values-to-a-variable-inside-mysql-triggers – mostruash

回答

0

使用INTO關鍵字周圍的選擇查詢http://dev.mysql.com/doc/refman/5.0/en/select-into.html

select examination_class_id into the_class_id from examinations where examination_id = the_last_inserted_id; 
select examination_class_year_id into the_year_id from examinations where examination_id = the_last_inserted_id; 
+0

那也行得通,但是這樣怎麼樣'insert into examination_data(ed_cs_id,ed_examination_id)(select cs_id from class_students其中cs_class_id = the_class_id AND cs_year_id = the_year_id),the_last_inserted_id);'。我試圖插入額外的列。我是否用'('和')''圍繞選擇語句。 –

+0

不確定括號,但它不會嚴重影響查詢。所以,如果您不確定,請添加它。否則,你的查詢是正確的,除了數據之前缺少關鍵字'VALUES'。 – sdespont