As the title says, I have an issue with the trigger + procedure.
What I'm trying to do it's a procedure + trigger that creates an email with the name and surnames only if when I'm trying to insert a student data w/o an email.
Basically where am stuck is, the code makes the fusion of name and surname and creates the email, but how do I place it before it inserts inside the table?
Best regards, Engineer Here's the code I have made:
use alumnesTriggers;
drop procedure if exists ex2;
delimiter //
create procedure ex2 (in nom varchar(50), in cognom1 varchar(50),
in cognom2 varchar(50), in domini varchar(50), out email varchar(50))
begin
set email := concat(nom,cognom1,cognom2,'@',domini,'.com');
#set @email := email;
#UPDATE alumnesEmail as ae SET ae.email = @email WHERE nom = @nom;
end //
delimiter ;
drop trigger if exists ex2_2_trigger;
DELIMITER $$
CREATE TRIGGER ex2_2_trigger before insert on alumnesEmail for each row begin
set @mail := new.email;
#if @mail := null or @mail='' then
set @id := new.id;
set @nom := new.nom;
set @cognom1 := new.cognom1;
set @cognom2 := new.cognom2;
call ex2(@nom,@cognom1,@cognom2,'gmail',@email);
UPDATE alumnesEmail SET new.email = @email;
#end if;
END $$
DELIMITER ;
INSERT INTO `alumnesEmail` (`id`, `nom`, `cognom1`, `cognom2`, `email`)
VALUES (80, 'a', 'a', 'a',null);
select * from alumnesEmail where id = 80;
select @email;
select * from alumnesEmail ;
but how do I place it before it inserts inside the table?
In a before
trigger, you just set new.email
to the target value. This modifies the value that is about to be written to the database.
Also, the procedure seems superfluous here.
The following code should do just what you want:
delimiter $$
create trigger ex2_2_trigger
before insert on alumnesemail
for each row
begin
if new.email is null or new.email = '' then
set new.email = concat(new.nom, new.cognom1, new.cognom2, '@gmail.com');
end if;
end $$
delimiter ;