Creating a BEFORE INSERT TRIGGER IN MYSQL - mysql

I need help creating a BEFORE INSERT TRIGGER on mySQL Bench. im new to this please.
CREATE TABLE `quincyninying`.`toytracking` (
`Toyid` INT NOT NULL,
`ToyName` VARCHAR(50) NULL,
`Toycost` DECIMAL NULL,
`ToyAction` VARCHAR(50) NULL,
`ActionDate` DATETIME NULL,
PRIMARY KEY (`Toyid`));
CREATE TABLE `quincyninying`.`toy` (
`Toyid` INT NOT NULL,
`ToyName` VARCHAR(50) NULL,
`Toycost` DECIMAL NULL,
PRIMARY KEY (`Toyid`));
Create a BEFORE INSERT trigger on the toy table that adds a record to the toytracking table with the information from the toy table record that is being INSERTED, hard coded ToyAction that will be ‘INSERT’ and the current Date and time the record is inserted.
ERROR 1054: Unknown column 'inserted' in 'NEW' SQL Statement:
CREATE DEFINER = CURRENT_USER TRIGGER `quincyninying`.`toy_BEFORE_INSERT` BEFORE INSERT ON `toy`
FOR EACH ROW
BEGIN
IF new.inserted THEN
SET #toyaction = 'DELETE';
ELSE
SET #toyaction = 'NEW';
END IF;
INSERT INTO `quincyninying`.`toytracking` (toyId, ToyName, ToyCost, Toyaction, ActionDate)
VALUES (new.toyid, new.Toyname, new.Toycost,#Toyaction, now());
END
It throws me an error saying " ERROR 1054: Unknown column 'inserted' in 'NEW' "

Get rid of the IF new.inserted test, since there's no column with that name, and just hard-code INSERT as the value for the ToyAction column as you stated in the requirements.
CREATE DEFINER = CURRENT_USER TRIGGER `quincyninying`.`toy_BEFORE_INSERT` BEFORE INSERT ON `toy`
FOR EACH ROW
BEGIN
INSERT INTO `quincyninying`.`toytracking` (toyId, ToyName, ToyCost, Toyaction, ActionDate)
VALUES (new.toyid, new.Toyname, new.Toycost, 'INSERT', now());
END

Try this:
DELIMITER $$
CREATE
TRIGGER toy_before_insert BEFORE INSERT
ON toy
FOR EACH ROW BEGIN
IF NEW.Toyaction THEN
SET #Toyaction = 'DELETE';
ELSE
SET #Toyaction = 'NEW';
END IF;
INSERT INTO toytracking (toyId, ToyName, ToyCost, Toyaction, ActionDate) VALUES (NEW.Toyid, NEW.ToyName, NEW.ToyCost, #Toyaction, NOW());
END$$
DELIMITER ;

Related

How to fix "Can't update table testtab in stored function/trigger

I have created a table
CREATE TABLE testtab (
`id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` bigint(20) DEFAULT NULL,
`food_id` int(11) DEFAULT NULL,
`created_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
Table contains below row
INSERT INTO testtab (`customer_id`, `food_id`, `created_date`)
VALUES ('433', '9', '2019-05-14 12:00:54');
Now the condition is for a specific customer_id there can be only one row with food_id either 8 or 9.
Now I try to add the below insert statement
INSERT INTO testtab (`customer_id`, `food_id`, `created_date`)
VALUES ('433', '8', '2019-05-14 12:00:54');
Now It should either get failed or get deleted immediately after inserted(record with tag_id=8).I have used the below trigger.But unfortunately i got error
Can't update table 'testtab' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
DELIMITER $$
USE `ipay`$$
DROP TRIGGER /*!50032 IF EXISTS */ `testtabTrigger`$$
CREATE
TRIGGER `testtabTrigger` AFTER INSERT ON `testtab`
FOR EACH ROW BEGIN
IF ((SELECT COUNT(*) FROM testtab WHERE food_id =9 AND customer_id = new.customer_id) =1 && new.food_id = 8) THEN
DELETE FROM testtab WHERE food_id = 8 AND customer_id = new.customer_id;
END IF;
END;
$$
DELIMITER ;
The idea is that you do something like this:
CREATE TRIGGER `testtabTrigger` BEORE INSERT ON `testtab`
FOR EACH ROW
BEGIN
IF (EXISTS (SELECT COUNT(*)
FROM testtab tt
WHERE tt.food_id = 9 AND
tt.customer_id = new.customer_id
) AND
new.food_id = 8
) THEN
signal sqlstate '45000' set message_text = 'Attempted insert of 8 when there is a 9';
END IF;
END;

#1442 - Can't update table ... in stored function/trigger because it is already used by statement which invoked this stored function/trigger

I have this situation:
Two table in two databases:
1st: `persone`.`T_Persone` that contain detailed information about workers plus two fields empty by default: `user_id` and `username`;
2nd: `joomla`.`fe48y_users` that contain information of user in the CMS Joomla including `id` and `username`.
I created a procedure that insert a new user in joomla and return user_id and username of new user created.
I also created also 2 triggers (on update and on insert) that call the procedure and set user_id and username on `T_Persone` table.
I also created a trigger on delete of `joomla`.`fe48y_users` that update `persone`.`T_Persone` and set null to `user_id` and `username` fields.
This is the procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `persone_users_upd`(IN `in_id` INT(10) UNSIGNED, IN `new_email` VARCHAR(255), IN `old_email` VARCHAR(255), OUT `out_user_id` INT(10) UNSIGNED, OUT `out_username` VARCHAR(255))
BEGIN
DECLARE has_email Boolean;
DECLARE my_user_id INT;
DECLARE my_username VARCHAR(255);
DECLARE my_name VARCHAR(255);
SELECT (CASE new_email WHEN '' THEN FALSE ELSE TRUE END) INTO #has_email;
IF #has_email THEN
SELECT CONCAT(`Nome`,' ',`Cognome`), COALESCE(`CF`,LOWER(SUBSTR(new_email, 1, INSTR(new_email, '#') - 1))) INTO #my_name, #my_username FROM `T_Persone` WHERE `IDPersona` = in_id;
IF new_email = old_email THEN
INSERT INTO `spmsf`.`fe48y_users` (`name`, `username`, `email`, `password`, `block`, `sendEmail`, `registerDate`, `lastvisitDate`, `activation`, `params`, `lastResetTime`, `resetCount`, `otpKey`, `otep`, `requireReset`) VALUES
(#my_name, #my_username, new_email, '<omissis>', 0, 1, NOW(), '0000-00-00 00:00:00', '', '{"admin_style":"","admin_language":"","language":"","editor":"","helpsite":"","timezone":"Europe/Rome"}', '0000-00-00 00:00:00', 0, '', '', 0) ON DUPLICATE KEY UPDATE `name` = VALUES(`name`), `email` = VALUES(`email`);
ELSE
UPDATE `spmsf`.`fe48y_users` SET `email` = #my_email WHERE `email` = new_email;
END IF;
SELECT `id`, `username` INTO #my_user_id, #my_username FROM `spmsf`.`fe48y_users` WHERE `email` = new_email;
INSERT IGNORE INTO `spmsf`.`fe48y_user_usergroup_map` (`user_id`,`group_id`) VALUES (#my_user_id, 10);
SET out_user_id=#my_user_id, out_username=#my_username;
END IF;
END
these are the triggers on `T_Persone`:
CREATE TRIGGER `persone_del` AFTER DELETE ON `T_Persone`
FOR EACH ROW BEGIN
IF OLD.`user_id` IS NOT NULL THEN
DELETE FROM `spmsf`.`fe48y_users` WHERE `id` = OLD.`user_id`;
DELETE FROM `spmsf`.`fe48y_user_usergroup_map` WHERE `user_id` = OLD.`user_id`;
END IF;
END
CREATE TRIGGER `persone_ins` BEFORE INSERT ON `T_Persone`
FOR EACH ROW BEGIN
CALL persone_users_upd(NEW.`IDPersona`,COALESCE(NEW.`Email`,NEW.`Email_alt`),COALESCE(NEW.`Email`,NEW.`Email_alt`), #user_id, #username);
SET NEW.`user_id` = #user_id, NEW.`username` = #username;
END
CREATE TRIGGER `persone_upd` BEFORE UPDATE ON `T_Persone`
FOR EACH ROW BEGIN
CALL persone_users_upd(NEW.`IDPersona`,COALESCE(NEW.`Email`,NEW.`Email_alt`),COALESCE(OLD.`Email`,OLD.`Email_alt`), #user_id, #username);
SET NEW.`user_id` = #user_id, NEW.`username` = #username;
END
and this is the trigger on `fe48y_users` delete:
CREATE TRIGGER `users_del` BEFORE DELETE ON `fe48y_users`
FOR EACH ROW BEGIN
DECLARE my_user_id Int;
SELECT COUNT(*) INTO #my_user_id FROM `personale`.`T_Persone` WHERE `user_id` = OLD.`id`;
IF #my_user_id > 0 THEN
UPDATE `personale`.`T_Persone` SET `user_id` = NULL, `username` = NULL WHERE `user_id` = OLD.`id`;
END IF;
END
SO, I have two problems:
1st: When I try to delete a user in `fe48y_users` I have the error
#1442 - Can't update table 'fe48y_users' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
2nd: When I insert a new person it don't appear in 'fe48y_users' but when I update it than appear.

MySQL Trigger Insert Before Not Firing

I'm trying to add a trigger for auditing to initialize a datetime field on an insert. Does anyone see what might be causing this trigger to not fire???
USE example;
CREATE TABLE USERS (
ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
FULLNAME VARCHAR(128) NOT NULL,
`PASSWORD` CHAR(88) NOT NULL,
EMAIL VARCHAR(128) NOT NULL,
FLAGS TINYINT UNSIGNED DEFAULT 0,
CREATED DATETIME,
UPDATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE INDEX(EMAIL),
PRIMARY KEY( ID )
);
DELIMITER $$;
CREATE TRIGGER USER_T BEFORE INSERT ON USERS FOR EACH ROW
BEGIN
SET NEW.CREATED = CURRENT_TIMESTAMP();
END;$$
DELIMITER ;
INSERT INTO USERS(FULLNAME, `PASSWORD`, EMAIL) VALUES('Admin', 'sQnzu7wkTrgkQZF+0G1hi5AI3Qmzvv0bXgc5THBqi7mAsdd4Xll27ASbRt9fEyavWi6m0QP9B8lThf+rDKy8hg==', 'root#localhost');
It looks like you are using the ; as a delimiter here
SET NEW.CREATED = CURRENT_TIMESTAMP();
END;$$
DELIMITER ;
Try this:
DELIMITER $$;
CREATE TRIGGER USER_T BEFORE INSERT ON USERS FOR EACH ROW
BEGIN
SET NEW.CREATED = CURRENT_TIMESTAMP();
END $$
DELIMITER ;

MySQL, trigger that generates primary key before insert a row

I'm trying to generate a primary key based on current date and time,
Here's my trigger:
DELIMITER $$
CREATE TRIGGER cuenta
BEFORE UPDATE ON cuenta
FOR EACH ROW
BEGIN
INSERT INTO cuenta VALUES (NULL);
SET NEW.NoCuenta = DATE_FORMAT(NOW(), '%000%d%m%y%h%i%s');
END$$
DELIMITER ;
My table cuenta:
NoCuenta, varchar(15), NOT NULL.
TipoCuenta, varchar(7),
saldo, float
IDCliente, int(8).
Then I try to insert:
insert into banco.cuenta(TipoCuenta, saldo, IDCliente)
VALUES('Debito','12500.5','1');
The result:
1 row(s) affected, 1 warning(s): 1364 Field 'NoCuenta' doesn't have a default value
But when I type select*from cuenta... NoCuenta field is empty.
And then when I try to insert a new row, it shows this:
Error Code: 1062. Duplicate entry '' for key 'PRIMARY'
Please HELP!!
Why are you inserting into the table in the trigger? Just try this:
DELIMITER $$
CREATE TRIGGER cuenta
BEFORE UPDATE ON cuenta
FOR EACH ROW
BEGIN
SET NEW.NoCuenta = DATE_FORMAT(NOW(), '%000%d%m%y%h%i%s');
END$$
DELIMITER ;

MySQL Trigger on after insert

I am new to MySQL. I have two tables total_loaner and available_loaner. I am trying to create a trigger for every new row added in total_loaner, I would also like to add that new row to available_loaner.
Here how my tables look like:
CREATE TABLE `total_loaner` (
`Kind` varchar(10) NOT NULL,
`Type` varchar(10) NOT NULL,
`Sno` varchar(10) NOT NULL,
PRIMARY KEY (`Sno`)
)
CREATE TABLE `available_loaner` (
`Kind` varchar(10) NOT NULL,
`Type` varchar(10) NOT NULL,
`Sno` varchar(10) NOT NULL,
`Status` char(10) NOT NULL DEFAULT '',
PRIMARY KEY (`Sno`)
)
My trigger does not seem to work.
CREATE TRIGGER new_loaner_added
AFTER INSERT ON 'total_loaner' for each row
begin
INSERT INTO available_loaner (Kind, Type, Sno, Status)
Values (new.Kind, new.Type, new.Sno, 'Available');
END;
In your case you can rewrite your trigger like this
CREATE TRIGGER new_loaner_added
AFTER INSERT ON total_loaner
FOR EACH ROW
INSERT INTO available_loaner (Kind, Type, Sno, Status)
VALUES (NEW.Kind, NEW.Type, NEW.Sno, 'Available');
Note:
single quotes removed from table name total_loaner, because quotes effectively makes it a string literal instead of a proper identifier. You can use back ticks if you want but it's unnecessary since it's not a reserved word and it don't contain any special characters.
since it's a one-statement trigger now you don't need to use DELIMITER command and BEGIN...END block
Here is SQLFiddle demo
You probably need to set your delimiter:
DELIMITER $$
CREATE TRIGGER new_loaner_added
AFTER INSERT ON `total_loaner` for each row
begin
INSERT INTO available_loaner (Kind, Type, Sno, Status)
Values (new.Kind, new.Type, new.Sno, 'Available');
END$$
DELIMITER ;
Right now, it's confusing the semi-colon at the end of the INSERT statement with the end of the CREATE TRIGGER statement.
This one worked for me, more simplified version..
CREATE TRIGGER new_loaner_added
AFTER INSERT ON `DB1`.`table_name`
FOR EACH ROW
INSERT INTO `DB2`.`table_name` (messageID, conversationID, fromJID)
VALUES (NEW.messageID,NEW.conversationID, NEW.fromJID);
AFTER INSERT ON `total_loaner`
Use backticks.