触发条件插入

时间:2014-06-23 19:19:26

标签: mysql

我在使用条件插入语句实现触发器时遇到了一些问题。我尝试过的没有条件语句的代码是

CREATE TRIGGER TR_BI_USERS after insert on USERS for each row 
  insert into PERMISSION(per_id,role_id,page_id,allow_y_n,created_by) 
  select d.user_id,d.role_id,c.page_id,'Y',d.created_by 
  from USERS as d cross join resource c 
  where d.user_id=new.user_id and d.role_id=1;

然而,当我尝试使用条件语句的类似外观触发器时,我收到错误。我试过的代码看起来像这样

CREATE TRIGGER TR_BI_USERS after insert on tourism_web.USERS for each row 
  begin 
    if new.role_id=1 then 
      insert into PERMISSION(per_id,role_id,page_id,allow_y_n,created_by) 
      select d.user_id,d.role_id,c.page_id,'Y',d.created_by 
      from USERS as d cross join resource c 
      where d.user_id=new.user_id; 
    else 
      insert into PERMISSION(per_id,role_id,page_id,allow_y_n,created_by) 
      select d.user_id,d.role_id,c.page_id,'N',d.created_by 
      from USERS as d cross join resource c 
      where d.user_id=new.user_id;
    end if;
  end;

请建议我在代码的后半部分应该对其进行修改以使其正常工作。感谢。

1 个答案:

答案 0 :(得分:0)

当您编写包含多个语句的触发器或过程时,您需要首先更改查询分隔符:

DELIMITER //
CREATE TRIGGER TR_BI_USERS after insert on tourism_web.USERS for each row 
  begin 
    if new.role_id=1 then 
      insert into PERMISSION(per_id,role_id,page_id,allow_y_n,created_by) 
      select d.user_id,d.role_id,c.page_id,'Y',d.created_by 
      from USERS as d cross join resource c 
      where d.user_id=new.user_id; 
    else 
      insert into PERMISSION(per_id,role_id,page_id,allow_y_n,created_by) 
      select d.user_id,d.role_id,c.page_id,'N',d.created_by 
      from USERS as d cross join resource c 
      where d.user_id=new.user_id;
    end if;
  end;
DELIMITER ;