4

Apparently MySQL have the really annoying restriction of not being able to update a table inside a trigger defined for that same table.
I'm using MySQL version 5.1 and I get the error: "Can't update table in stored function/trigger because it is already used by statement which invoked this function/trigger".

What I have is this:

create table folder(
    id int unsigned not null auto_increment PRIMARY KEY ,
    name varchar(100) not null ,
    parentId int unsigned not null
) ;

It's a hierarchical folder structure. A folder has a name and possibly a parent folder (if not then parentId is zero).
When a folder is deleted I need to change the parentId of all subfolders which were inside it, so that they don't become children of a nonexistent folder.

It's rather simple (almost trivial):

CREATE DEFINER=root@localhost TRIGGER onFolderDelete after delete ON folder
FOR EACH ROW update folder set parentId=0 where parentId=old.id ;

However, such a simple trigger is not allowed by MySQL because, as I said above, you cannot update a table inside its own trigger.

Is there any way of implementing such a trigger by emulating its effects in some way??

P.S.: Please dont suggest sending both statements in sequence (the DELETE and the UPDATE). That's obviously the last solution if nothing else is possible.

Edit:
I'm using MyISAM engine (performance reasons) so I can't use foreign keys.

GetFree
  • 40,278
  • 18
  • 77
  • 104

1 Answers1

3

Can't you add a foreign key with ON DELETE SET NULL (or DEFAULT) ?
UPDATE (DEFAULT is still not implemented;SET NULL is the only option...)
So you will have something like

create table folder(
id int unsigned not null auto_increment PRIMARY KEY ,
name varchar(100) not null ,
parentId int unsigned null ,
FOREIGN KEY(parentId) REFERENCES folder(id) ON UPDATE CASCADE ON DELETE SET NULL      
) ;
a1ex07
  • 36,826
  • 12
  • 90
  • 103
  • I'm using the MyISAM engine which doesn't support foreign keys. This is for a high traffic website so MyISAM is required for performace reasons. – GetFree Jun 28 '11 at 15:42