MySQL Trigger on after insert - mysql

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.

Related

After Creating after update trigger i cant update any

DROP TABLE IF EXISTS Sales;
CREATE TABLE Sales (
id INT AUTO_INCREMENT,
product VARCHAR(100) NOT NULL,
quantity INT NOT NULL DEFAULT 0,
fiscalYear SMALLINT NOT NULL,
fiscalMonth TINYINT NOT NULL,
CHECK(fiscalMonth >= 1 AND fiscalMonth <= 12),
CHECK(fiscalYear BETWEEN 2000 and 2050),
CHECK (quantity >=0),
UNIQUE(product, fiscalYear, fiscalMonth),
PRIMARY KEY(id)
);
DROP TABLE IF EXISTS log;
CREATE TABLE log (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
text VARCHAR(100)
);
Triggers
CREATE DEFINER=`root`#`localhost` TRIGGER `sales_AFTER_UPDATE` AFTER UPDATE ON `sales`
FOR EACH ROW
BEGIN
INSERT INTO log VALUES(NOW(),CONCAT('Update Student Record ', OLD.quantity));
END
UPDATE test for.sales SET quantity = 36
WHERE (id = 1);
ERROR 1136: 1136: Column count doesn't match value count at row 1
Iam new in mySQL Please help
You should specify columns in INSERT statement in your trigger explicitly, as you do not set all values in a row (auto incremented column excluded).
So it would be
INSERT INTO log(timestamp, text) VALUES (NOW(),CONCAT('Update Student Record ', OLD.quantity));
You have some errors.
First based on your trigger you need another column on log table which is as following
quantity INT NOT NULL DEFAULT 0
Second , do not use Keywords and Reserved Words like text and timestamp, it is a bad practice. If you do please put it inside backticks
Third your insert statement should be
INSERT INTO log(`timestamp`,`text`,quantity) VALUES(NOW(),'Update Student Record', OLD.quantity);
there is no need for CONCAT.
Fourth,
`sales`
table is not the same as Sales table, because you have used backticks.
Full working trigger below:
DELIMITER //
CREATE TRIGGER `sales_AFTER_UPDATE` AFTER UPDATE ON Sales
FOR EACH ROW
BEGIN
INSERT INTO log(`timestamp`,`text`,quantity) VALUES(NOW(),'Update Student Record', OLD.quantity);
END//
DELIMITER ;
Check working demo:
https://www.db-fiddle.com/f/iqwShcHK3AGJvU4MDbxDku/0

Trigger dows not let me insert data in mysql

i am trying to get used to triggers. I created a small database and a trigger. When i go to insert something in ship category it does not let me do it.If i drop the trigger with the same commend i can insert values at the table. I get this error: #1048 - Column 'IMO' cannot be null
My trigger code is:
/*ship insert*/
DELIMITER //
CREATE TRIGGER `ship_insert_logs`
AFTER INSERT ON `ship`
FOR EACH ROW
BEGIN
DECLARE ship_IMO INTEGER;
SET ship_IMO=new.IMO;
INSERT INTO ship_logs VALUES (null, concat('A new row is inserted with IMO ', ship_IMO, 'at',
date_format(now(), '%d-%m-%y %h:%i:%s %p')));
END //
DELIMITER ;
and ship table is:
CREATE TABLE ship(
department_id INTEGER NOT NULL,
IMO BIGINT PRIMARY KEY NOT NULL,
Latitude DOUBLE PRECISION NOT NULL,
Longitude DOUBLE PRECISION NOT NULL,
current_speed DOUBLE PRECISION NOT NULL,
heading VARCHAR (30),
status VARCHAR(30),
FOREIGN KEY(department_id) REFERENCES department (department_id) ON UPDATE CASCADE
);
while ship_logs table is:
CREATE TABLE ship_logs(
IMO BIGINT PRIMARY KEY NOT NULL,
audit_description VARCHAR(500)
);

MYSQL Trigger - storing updated table data

I have a table that tracks the number of hours an employee took on a job.
CREATE TABLE HOURLYWORKLOG (
EMPLOYEEREF INT(5) NOT NULL,
ORDERREF INT(5) NOT NULL,
HOURSWORKED VARCHAR(10),
TOTALPAY NUMERIC(10),
NOTES VARCHAR(10),
CONSTRAINT HOURLYWORKLOG_EMPLOYEES_FOREIGN_KEY FOREIGN KEY (EMPLOYEEREF) REFERENCES EMPLOYEES (EMPLOYEEREF),
CONSTRAINT HOURLYWORKLOG_ORDERS_FOREIGN_KEY FOREIGN KEY (ORDERREF) REFERENCES WORKORDER (ORDERREF));
I am looking to create a trigger that stores this data in a separate table if the hoursworked column is updated. Reading around, I can't see anything that explains what I need to do, at least I can't understand the steps involved after reading. As such my current solution is through creating a mirrored table (with a different name)
CREATE TABLE MODIFIEDHOURLYWORKLOG (
EMPLOYEEREF INT(5) NOT NULL,
ORDERREF INT(5) NOT NULL,
HOURSWORKED VARCHAR(10),
TOTALPAY NUMERIC(10),
NOTES VARCHAR(10));
And then creating a trigger as such
CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG
AFTER INSERT
AS
BEGIN
INSERT INTO MODIFIEDHOURLYWORKLOG
(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
SELECT I.EMPLOYEEREF, I.ORDERREF, I.HOURSWORKED, I.TOTALPAY, I.NOTES
FROM HOURLYWORKLOG T
INNER JOIN INSERTED I ON T.EMPLOYEEREF-I.EMPLOYEEREF
END;
This obviously isn't working and is throwing up errors that my syntax is incorrect. I'm not sure how to write a trigger to transfer the data from the original table into the secondary one basically...
Thank you for any help.
You want to use trigger syntax for MySQL, not SQL Server. Something like this:
DELIMITER $$
CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG AFTER INSERT
FOR EACH ROW AS
BEGIN
INSERT INTO MODIFIEDHOURLYWORKLOG(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
SELECT NEW.EMPLOYEEREF, NEW.ORDERREF, NEW.HOURSWORKED, NEW.TOTALPAY, NEW.NOTES
FROM DUAL
WHERE NOT NEW.HOURSWORKED <=> OLD.HOURSWORKED;
END;$$
DELIMITER ;
CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG
after update
for each row
AS
BEGIN
INSERT INTO MODIFIEDHOURLYWORKLOG
(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
SELECT NEW.EMPLOYEEREF, NEW.ORDERREF, NEW.HOURSWORKED, NEW.TOTALPAY,
NEW.NOTES
from dual where NEW.HOURSWORKED != OLD.HOURSWORKED
END;
/

Creating a BEFORE INSERT TRIGGER IN 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 ;

Inserting new random uuid() in two tables in every insert

I have created two tables which i want to insert similar data in.
CREATE TABLE one(
one_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (one_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE two(
two_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (two_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
every time in run insert.
To do that,i am using transactions
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
This does not produce new values on new inserts.It however inserts the same data in the field name as i wanted.
How can i make this work?.
I don't see a need to move to transactions in order to do that, just add an before insert trigger to the table .
Something like :
CREATE TRIGGER `ONE_TABLE_TRIGG` BEFORE INSERT ON `one`
FOR EACH
ROW BEGIN
SET NEW.name= UUID( );
END ;
You can check if it's null before doing that. do this on both tables and you're good or add insert to the other table on 1 trigger.
I solved it without much complexities by having several having several transaction statements in the same file
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
/*
Etc
*/