Skip to content
Advertisement

MYSQL Trigger update not working as expected when value is updated

Looking to use a trigger on a MYSQL table when the row is updated, anytime the row is updated. Only setting the id if the id field is null

create trigger before_id_update
BEFORE UPDATE
ON USERS for each row
BEGIN
if id iS NULL THEN 
SET id = username
END IF;
END

Currently nothing is happening when the table row is updated

Advertisement

Answer

Your code should raise a syntax error, since id and username are undefined variables. If you want to access the values on the updated row, use pseudo-tables NEW or OLD.

You also need a delimiter statement at the beginning of your code, and the set command should be terminated with a semi-colon.

You presumably want:

delimiter //

create trigger before_id_update
before update on users 
for each row
begin
    if new.id is null then 
        set new.id = new.username;
    end if;
end
//

delimiter ;

Note that this only makes sense if both id and username have the same datatype (which is not obvious from their names).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement