views:

30

answers:

1

Hello!

I want to be sure, that there are no children of children in my datatable. So if I have a parent item A, and a child item B (B.parent = A), and I try to insert a child item C to the item B (C.parent = B), this trigger have to prevent it and set the parent_id of C to A (C.parent = A). I need only 2 levels in my table (parent-child), and no grandpas.

There is my sample, that doesn't work:

DELIMITER //
CREATE TRIGGER parent_control BEFORE insert ON reports
FOR EACH ROW BEGIN
IF new.parent_id is not null THEN
  set @parent_parent_id = new.parent_id;
  SELECT parent_id FROM reports INTO parent_parent_id WHERE report_id = new.parent_id;
  IF @parent_parent_id is not null THEN
    SET new.parent_id = @parent_parent_id;
  END IF;
END IF;
END; 

It says: #1327 - Undeclared variable: parent_parent_id

A: 

might want to check field names and datatypes etc but something like this might work

delimiter #

create trigger reports_before_ins_trig before insert on reports
for each row
proc_main:begin

declare pid smallint unsigned default null;

  if new.parent_id is null then
    leave proc_main;
  end if;

  select parent_id into pid from reports where report_id = new.parent_id;

  if pid is not null then 
    set new.parent_id = pid;
  end if;

end proc_main #

delimiter ;
f00