触发器中的变量声明

时间:2014-01-25 09:43:13

标签: mysql triggers

如何声明temp变量,虽然我已经研究过语法,但据我说,它是对的,但它也显示错误:Undefined temp and t.

CREATE TRIGGER check_reciever BEFORE INSERT
ON one_to_one FOR each row
BEGIN
select employee_id into temp from employee_master where employee_id = NEW.reciever_id;
IF temp!=0 THEN
insert into one_to_one values(new.message_id,new.reciever_id,new.read);
ELSE
   select count(*) into t from parent_master where parent_id=new.reciever_id;
   IF t!=0 THEN
     insert into one_to_one values(new.message_id,new.reciever_id,new.read);
   END IF;
END IF;
END

1 个答案:

答案 0 :(得分:0)

你错过了用于声明变量的DECLARE子句(可以从其名称中猜到):

CREATE TRIGGER check_reciever BEFORE INSERT
ON one_to_one FOR each row
-- Begining of the DECLARE section you're missing
DECLARE
    temp NUMBER;
    t NUMBER;
-- End of the missing section
BEGIN
    select employee_id into temp from employee_master where employee_id = NEW.reciever_id;
    IF temp!=0 THEN
        insert into one_to_one values(new.message_id,new.reciever_id,new.read);
    ELSE
        select count(*) into t from parent_master where parent_id=new.reciever_id;
        IF t!=0 THEN
           insert into one_to_one values(new.message_id,new.reciever_id,new.read);
        END IF;
   END IF;
END

编辑:以上是Oracle解决方案,根据OP的标签。对于MySQL,DECLARE语法略有不同:

CREATE TRIGGER check_reciever BEFORE INSERT
ON one_to_one FOR each row
BEGIN
    -- Declarations
    DECLARE temp NUMERIC;
    DECLARE t NUMERIC;
    -- End declarations
    select employee_id into temp from employee_master where employee_id = NEW.reciever_id;
    IF temp!=0 THEN
        insert into one_to_one values(new.message_id,new.reciever_id,new.read);
    ELSE
        select count(*) into t from parent_master where parent_id=new.reciever_id;
        IF t!=0 THEN
           insert into one_to_one values(new.message_id,new.reciever_id,new.read);
        END IF;
   END IF;
END