MariaDB version 10.1.16.
I can't find what is the problem in the below trigger:
DROP TRIGGER IF EXISTS `insert_customer`;
DELIMITER |
CREATE TRIGGER `insert_customer` AFTER INSERT ON `installations`
FOR EACH ROW BEGIN
DECLARE customerId INT DEFAULT NULL;
DECLARE versionCode INT DEFAULT NULL;
SELECT c.`id`, c.`version_code` INTO #customerId, #versionCode FROM `customers` c WHERE c.`phone` = NEW.`phone`;
IF #customerId IS NULL THEN
INSERT INTO `customers` (`phone`, `imei`, `platform`, `version_code`, `created`, `modified`) VALUES (NEW.`phone`, NEW.`imei`, NEW.`platform`, NEW.`version_code`, NOW(), NOW());
ELSEIF NEW.`version_code` > #versionCode THEN
UPDATE `customers` SET `version_code` = NEW.`version_code` WHERE `id` = #customerId;
END IF;
END;|
DELIMITER ;
It says 1064 - syntax error near THEN INSERT but I'm sure the problem is elsewhere. Please help.
Related
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;
I try to create stored procedure in MySQL:
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int
select _authorId = id from Authors where name = _authorName
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName)
SELECT _authorId = SCOPE_IDENTITY()
END IF
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId)
END;
But I get the error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'select _authorId = id from Authors where name = _authorName IF
(_authorId is nul' at line 1
Seems like script is too large to be executed. Line just broken near: IF (_authorId is null) THEN -- IF (_authorId is nul
You have a problem with your delimiters. By default it's ";". But you need internal delimiter, so :
DELIMITER |
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int;
select _authorId = id from Authors where name = _authorName;
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName);
SELECT _authorId = LAST_INSERT_ID();
END IF;
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId);
END|
Its working code on SQLYOG: Please try in this way
DELIMITER $$
CREATE /*[DEFINER = { user | CURRENT_USER }]*/ PROCEDURE `test`.`sp_attachAuthorToBook`(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
DECLARE _authorId INT;
SELECT id INTO _authorId FROM Authorss WHERE `name` = _authorName;
IF _authorId IS NULL THEN
INSERT INTO Authorss(`name`) SELECT _authorName;
SET _authorId = LAST_INSERT_ID();
END IF;
INSERT INTO Book_Authors(bookID, authorID) SELECT _bookId, _authorId;
END$$
DELIMITER ;
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.
I've been working on a trigger for MySQL for a couple hours now, and I can't figure out what's wrong.
Here is my table structure:
CREATE TABLE IF NOT EXISTS `RentalVideo` (
`OrderID` int(11) NOT NULL,
`VideoBarcode` int(11) NOT NULL,
`RentalReturned` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`OrderID`,`VideoBarcode`),
KEY `RentalVideo_VideoBarcode_FK` (`VideoBarcode`)
)
Here's some sample data:
INSERT INTO `RentalVideo` (`OrderID`, `VideoBarcode`, `RentalReturned`) VALUES
(1, 223823, 0),
(1, 447956, 0),
(3, 705481, 0),
(4, 988908, 0),
(5, 143375, 0);
Here's the trigger that's not working:
CREATE
TRIGGER `RENT_FIVE_VIDEOS_MAX` BEFORE INSERT
ON `bollywoo_video`.`RentalVideo`
FOR EACH ROW BEGIN
-- variable declarations
DECLARE vRentedVideos int;
DECLARE vCustomer int;
-- trigger code
SELECT RentalOrder.CustID
FROM RentalOrder
WHERE RentalOrder.OrderID = NEW.OrderID
INTO vCustomer;
SELECT COUNT(*)
FROM RentalOrder, RentalVideo
WHERE RentalOrder.CustID = vCustomer
AND RentalVideo.RentalReturned = 0
AND RentalOrder.OrderId = RentalVideo.VideoID
INTO vRentedVideos;
IF vRentedVideos >= 5 THEN
CALL RAISE_APPLICATION_ERROR(-2000, 'Cannot checkout more than 5 videos');
END IF;
END
And last but not least, this is the error I'm getting:
Error
SQL query:
CREATE TRIGGER `RENT_FIVE_VIDEOS_MAX` BEFORE INSERT ON `bollywoo_video`.`RentalVideo`
FOR EACH
ROW BEGIN -- variable declarations
DECLARE vRentedVideos INT;
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 6
The error appears to be occurring right before DECLARE vRentedVideos int;
Remove semicolon and try this
DELIMITER $$
CREATE
TRIGGER `RENT_FIVE_VIDEOS_MAX` BEFORE INSERT
ON `bollywoo_video`.`RentalVideo`
FOR EACH ROW BEGIN
...
END$$
DELIMITER ;
I created this trigger:
CREATE TABLE `Invitations`
( `userId` varchar(255) NOT NULL, `name` varchar(255) DEFAULT NULL,
`status` varchar(1) DEFAULT NULL, `userId_inv` varchar(255) NOT NULL,
PRIMARY KEY (`userId`,`userId_inv`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1
CREATE TRIGGER `Invitation_001_after_trig` AFTER INSERT ON `invitation_001`
FOR EACH ROW
BEGIN
IF ((new.userId,'001') NOT EXISTS (SELECT `userId`,`userId_inv` FROM `Invitations`
WHERE `userId`= new.userId AND `userId_inv` = '001' LIMIT 1))
THEN
INSERT INTO `Invitations`(`userId`, `name`,`status`,`userId_inv`)
values (new.userId, new.name,new.status,'001');
DELETE FROM `invitation_001` WHERE `status` = 'a';
END IF;
END;
It did not work. I had this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'EXISTS (SELECT userId,userId_inv FROM Invitations WHERE
userId= new.user' at line 1
So could you help me.
I resolved the problem with this trigger:
CREATE TRIGGER `Invitation_001_after_trig` AFTER INSERT ON `invitation_001`
FOR EACH ROW
BEGIN
INSERT INTO `Invitations` (`userId`, `name` ,`status` ,`userId_inv`) SELECT * FROM
invitation_001 iv WHERE
NOT EXISTS (SELECT 1 FROM `Invitations` ivs WHERE ivs.`userId` = iv.`userId` AND
ivs.`userId_inv` = iv.`userId_inv`) AND iv.`userId_inv`='001';END;
Now I've an other issue. I would like to execute a query from a Concat String in a trigger but until now I did not succeed so here is my code:
CREATE TRIGGER `InvitationS_after_trig` AFTER INSERT ON `Invitations`
FOR EACH ROW
BEGIN
if(new.status ='c' OR new.status ='r')
BEGIN
SET #query = CONCAT("INSERT INTO", Invetations.userId,"values(new.userId,new.name,new.status,new.userId_inv);");
PREPARE stmt1 FROM #query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END IF;
END;
I resolved the syntax problem but I now have an other one:
Dynamic SQL is not allowed in stored function or trigger
I'm using MySQL version 5.1.69.
Finally I give up, I will resolve this problem using java Fonction