如何更正此触发功能?

时间:2016-09-12 17:20:50

标签: mysql sql triggers

create trigger trig1
    -> after insert on student
    -> for each row
    -> when (new.name="rgb")
    -> begin
    -> insert into class ("ug1",1)
    -> end;

它告诉我声明附近出了点问题。你能帮我找到它吗?

desc class;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(40) | YES  |     | NULL    |       |
| section | int(11)     | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.06 sec)

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| roll  | int(11)     | YES  |     | NULL    |       |
| name  | varchar(40) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

这些是对这两个表的描述。

3 个答案:

答案 0 :(得分:1)

您的触发器声明应如下所示。见Trigger Syntax and Examples

create trigger trig1
    -> after insert on student
    -> for each row
    -> begin                        //begin should come first
    -> if (new.name='rgb')          //use IF condition
    -> insert into class values('ug1',1); //missing values keyword here
    -> end if;
    -> end;

答案 1 :(得分:0)

正确的解决方案是:

DELIMITER @
-> create trigger trig1
-> after insert on student
-> for each row
-> begin
-> if ( new.name = 'rgb')
-> then
-> insert into class values ('ug1',1);
-> end if;
-> end;
 @

答案 2 :(得分:0)

您在通过CLI创建触发器时缺少分隔符

以下是创建它的语法 -

delimiter //
create trigger trig1 
after insert on student
for each row 
begin
  if new.name='rgb' then
    insert into `class` ('ug1',1);
  end if ;
end//

delimiter;