Please refer the below image
I want to create an After Insert trigger on Ongoing_Fees table where it updates the VAT table. However before it insert data to the VAT table, it should check whether the VAT field of the particular Portfolio is true. Ongoing_Fees table has the foreign key access to the Portfolio table, so it can access the related portfolio.
Below is what I have tried
DELIMITER $$
CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees` FOR EACH ROW
BEGIN
DECLARE `vat` Boolean;
`vat` = SELECT VAT from Portfolio WHERE Portfolio.idPortfolio = New.idPortfolio;
IF (`vat` == true) THEN
INSERT INTO VAT VALUES (100, current_Timestamp, New.idPortfolio, New.idOngoing_Fees)
END;
But of course, it has an error
#1064 - 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 VAT from Portfolio WHERE Portfolio.idPortfolio = New.idPortfolio;
Try:
DELIMITER $$
CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees`
FOR EACH ROW
BEGIN
DECLARE `_vat` BOOL;
SET `_vat` := (SELECT `VAT` FROM `Portfolio` WHERE `Portfolio`.`idPortfolio` = NEW.`idPortfolio`);
IF (`_vat` = TRUE) THEN
INSERT INTO `VAT` (
`Amount`,
`current_timestamp`,
`Portfolio_idPortfolio`,
`Ongoing_Fees_idOngoing`
)
VALUES (
100,
CURRENT_TIMESTAMP(),
NEW.`idPortfolio`,
NEW.`idOngoing_Fees`
);
END IF;
END$$
DELIMITER ;
A shorter version:
DELIMITER $$
CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees`
FOR EACH ROW
BEGIN
INSERT INTO `VAT` (
`Amount`,
`current_timestamp`,
`Portfolio_idPortfolio`,
`Ongoing_Fees_idOngoing`
)
SELECT
100,
CURRENT_TIMESTAMP(),
NEW.`idPortfolio`,
NEW.`idOngoing_Fees`
FROM
DUAL
WHERE
TRUE = (SELECT
`VAT`
FROM
`Portfolio`
WHERE
`Portfolio`.`idPortfolio` = NEW.`idPortfolio`
);
END$$
DELIMITER ;
Related
When new user registered automatically its permissionID will be 1. It's just that simple, but mysql syntax errors are killing me. Please help
CREATE TRIGGER `user_default_role`
AFTER INSERT ON `users`
FOR EACH ROW
BEGIN
DECLARE #userID int;
SET #userID = (SELECT userID FROM inserted LIMIT 1);
INSERT INTO `user_permission` (`userID`,`permissionID`,`created_at`,`updated_at`) VALUES (#userID,1 ,NOW(),null);
END
This is the error:
#1064 - 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 '#userID int' at line 5
EDIT: I didn't know about DELIMETER and NEW instead of inserted. Thank you for all who responded so quickly. Here is the updated code:
DELIMITER $$
CREATE TRIGGER `user_default_role` AFTER INSERT ON `users`
FOR EACH ROW
BEGIN
INSERT INTO `user_permission` (`userID`, `permissionID`, `created_at`, `updated_at`)
VALUES (new.userID, 1, NOW(), null);
END;$$
DELIMITER ;
inserted is something from SQL Server, but otherwise your syntax really does suggest MySQL. This may work for you:
DELIMITER $$
CREATE TRIGGER `user_default_role` AFTER INSERT ON `users`
FOR EACH ROW
BEGIN
INSERT INTO `user_permission` (`userID`, `permissionID`, `created_at`, `updated_at`)
VALUES (new.userId, 1, NOW(), null);
END;$$
DELIMITER ;
You are getting syntax error because of following the reasons:
1- Missing Delimiters.
2- Session variable(starting from #) cannot be declared.you can directly set the values to them.
3- There is no inserted table in MySQL where triggers temporary inserts data.You can access inserted values using NEW.
DELIMITER $$
CREATE TRIGGER `user_default_role`
AFTER INSERT ON `users`
FOR EACH ROW
BEGIN
SET #userID =NEW.userID;
INSERT INTO `user_permission` (`userID`,`permissionID`,`created_at`,`updated_at`) VALUES (#userID,1 ,NOW(),null);
END$$
DELIMITER ;
I have a trigger which is working fine.
CREATE TRIGGER crm_listings__au
AFTER UPDATE
ON crm_listings FOR EACH ROW
INSERT INTO crm_listings_versions
SELECT
'update', NULL, NOW(), NULL, d.*
FROM
crm_listings AS d
WHERE
d.id = NEW.id;
Now I want to keep track of the field column name also. I am thinking I could not do in above query so I changed to below trigger
CREATE TRIGGER crm_listings__au
BEFORE UPDATE
ON crm_listings
FOR EACH ROW
BEGIN
IF OLD.type != NEW.type
THEN
INSERT INTO crm_listings_versions
SELECT
'update', NULL, NOW(), 'type', d.*
FROM
crm_listings AS d
WHERE
d.id = NEW.id;
END IF;
IF OLD.price != NEW.price
THEN
INSERT INTO crm_listings_versions
SELECT
'update', NULL, NOW(), 'price', d.*
FROM
crm_listings AS d
WHERE
d.id = NEW.id;
END IF;
END;
$$
When I run this code, I get 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 '' at line 10
UPDATE:
I followed this post on stackoverflow
#kordirko: Can you please explain a little bit?
Please study the documentation: http://dev.mysql.com/doc/refman/5.7/en/stored-programs-defining.html
If you use the mysql client program to define a stored program
containing semicolon characters, a problem arises. By default, mysql
itself recognizes the semicolon as a statement delimiter, so you must
redefine the delimiter temporarily to cause mysql to pass the entire
stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command. The
following example shows how to do this for the dorepeat() procedure
just shown. The delimiter is changed to // to enable the entire
definition to be passed to the server as a single statement, and then
restored to ; before invoking the procedure. This enables the ;
delimiter used in the procedure body to be passed through to the
server rather than being interpreted by mysql itself.
Simple example - I am using MySql Workbench and have copied and pasted your trigger. First some dummy tables:
create table crm_listings(
id int,
type int,
price int
);
create table crm_listings_versions(
ttype varchar(100),
something varchar(100),
d date,
something1 varchar(100),
id int,
type int,
price int
);
And now I run your code without DELIMITER
CREATE TRIGGER crm_listings__au BEFORE UPDATE ON crm_listings
FOR EACH ROW
BEGIN
IF OLD.type != NEW.type
THEN
INSERT INTO crm_listings_versions SELECT 'update', NULL, NOW(), 'type', d.* FROM crm_listings AS d WHERE d.id = NEW.id;
END IF;
IF OLD.price != NEW.price
THEN
INSERT INTO crm_listings_versions SELECT 'update', NULL, NOW(), 'price', d.* FROM crm_listings AS d WHERE d.id = NEW.id;
END IF;
END;
$$
Error Code: 1064. 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 '' at line 10 0.000 sec
Outcome = Error
Then the same, but with the DELIMITER command:
DELIMITER $$
CREATE TRIGGER crm_listings__au BEFORE UPDATE ON crm_listings
FOR EACH ROW
BEGIN
IF OLD.type != NEW.type
THEN
INSERT INTO crm_listings_versions SELECT 'update', NULL, NOW(), 'type', d.* FROM crm_listings AS d WHERE d.id = NEW.id;
END IF;
IF OLD.price != NEW.price
THEN
INSERT INTO crm_listings_versions SELECT 'update', NULL, NOW(), 'price', d.* FROM crm_listings AS d WHERE d.id = NEW.id;
END IF;
END;
$$
DELIMITER ;
0 row(s) affected
Outcome = Success
CREATE TRIGGER b_I_O AFTER UPDATE ON book
FOR EACH ROW
BEGIN
IF (OLD.status IS NOT NULL AND NEW.status IS NOT NULL AND NEW.status != OLD.status ) THEN
INSERT INTO book_in_out (astatus, bid, time) VALUES(NEW.status, OLD.id, NOW());
END IF;
END;
First post here after hours of searching.
I'm trying to insert into book_in_out using trigger after updating booking table, I was able to do this but if I update bookName the trigger will try to run.
I only want the trigger to run only when status column changes. default value for status column is NULL
Below is the error i keep getting:
#1064 - 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 '' at line 5
You may try this
delimiter //
CREATE TRIGGER b_I_O AFTER UPDATE ON book
FOR EACH ROW
BEGIN
IF (OLD.status IS NOT NULL AND NEW.status IS NOT NULL AND NEW.status != OLD.status ) THEN
INSERT INTO book_in_out (`astatus`, `bid`, `time`) VALUES(NEW.status, OLD.id, NOW());
END IF;
END;//
delimiter ;
Try to manually specify delimeter for your trigger so it won't be confused with semicolons used within BEGIN/END, i.e.
DELIMITER //
CREATE TRIGGER b_I_O AFTER UPDATE ON book
FOR EACH ROW
BEGIN
IF (OLD.status IS NOT NULL AND NEW.status IS NOT NULL AND NEW.status != OLD.status ) THEN
INSERT INTO book_in_out (astatus, bid, time) VALUES(NEW.status, OLD.id, NOW());
END IF;
END;//
I'm doing a table where I store the last time the users do login/logout. Just one row storing an Id, the action as a bit field and the moment as a DATETIME. My idea is to do a stored procedure to make an insert when the user is new and an update when the user exists. I've done this code:
DELIMITER $$
CREATE PROCEDURE sp_LastAction(in id_in int, accion_in bit)
begin
SELECT #CONT:= IdUsuario FROM login WHERE IdUsuario = id_in;
IF NOT #CONT then
INSERT INTO login(IdUsuario, Fecha, Accion)
values (id_in, NOW(), accion_in);
ELSE
UPDATE login SET Fecha = NOW(), Accion = accion_in
WHERE IdUsuario = id_in LIMIT 1;
end IF;
end$$
DELIMITER ;
But when I call the procedure it doesn't do anything, just returns the variable as a void field.
You can make a UPSERT.
CREATE PROCEDURE `sp_LastAction`(id_in int, accion_in bit)
BEGIN
INSERT INTO `login` (`idusuario`, `fecha`, `accion`) VALUES (id_in, now(), accion_in)
ON DUPLICATE KEY UPDATE `fecha` = now(), `accion` = accion_in;
END //
Here's an example: SQL Fiddle
I want to check the existance of specific record in db table, if it's exist then update if not I want to add new record
I am using stored procedures to do so, First I make update stetement and want to check if it occurs and return 0 then there's no record affected by update statement and that means the record does not exist.
I make like this
DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11), IN privilegeId int(11), IN deletedBy int(11))
BEGIN
DECLARE isExist int;
isExist = update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` = CURRENT_TIMESTAMP() where `user_id`= userId and `privilege_id`=privilegeId;
IF isExist == 0 THEN
insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );
END IF;
END //
DELIMITER ;
This error occur with me
#1064 - 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 '= update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time' at line 6
Is the way I am working is supported by mysql?
I solve the problem, I had 2 prblems
ROW_COUNT() is used to get the number of rows affected in insert, update or delete statements.
Equals comparison in stored procedure is = not ==
The correct stored procedure is
DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11), IN privilegeId int(11), IN deletedBy int(11))
BEGIN
DECLARE count int default -1;
update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` = CURRENT_TIMESTAMP() where `user_id`= userId and `privilege_id`=privilegeId;
SELECT ROW_COUNT() into count ;
IF count = 0 THEN
insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );
END IF;
END //
DELIMITER ;
Use the INSERT IGNORE statement instead. I assume that your table has (user_id, privilege_id) as a unique key.
insert ignore into user_privileges (user_id,privilege_id,`mode,date_time_assigned,updated_by)
values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy )
on duplicate key update mode='d', date_time_assigned=now(),updated_by=deletedBy