mysql TRIGGER update field after update - mysql

i have 2 table today_plan and kiln_master.
after pattern and itemno inserted to today_plan then need to select matching yeild from kiln_master table and update this value to yeild field in today_plan.
i have created a trigger
CREATE TRIGGER update_yeild AFTER INSERT ON today_plan
FOR EACH ROW UPDATE today_plan
SET yeild= (SELECT kiln_master.yeild from kiln_master,today_plan WHERE today_plan.itemno = kiln_master.item AND today_plan.pattern = kiln_master.pattern ) WHERE itemno=new.itemno AND pattern=new.pattern
what part is wrong with my code
today_plan
DROP TABLE IF EXISTS decsys.today_plan;
CREATE TABLE `today_plan` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`belt` varchar(25) NOT NULL,
`distant` varchar(25) NOT NULL,
`pjtno` varchar(15) DEFAULT NULL,
`pattern` varchar(25) NOT NULL,
`itemno` varchar(25) NOT NULL,
`pro_qty` varchar(25) NOT NULL,
`act_qty` varchar(25) NOT NULL,
`yeild` varchar(25) NOT NULL,
`remark` varchar(100) NOT NULL,
`shipment` varchar(15) NOT NULL,
`temp` varchar(15) NOT NULL,
`fire_date` date NOT NULL,
`kiln` varchar(10) DEFAULT NULL,
`kiln_plan` varchar(15) NOT NULL,
`kiln_act` varchar(15) NOT NULL,
`ins_date` date NOT NULL,
`ins_act` varchar(15) NOT NULL,
`plandate` date NOT NULL,
`ship_date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
kiln_master
DROP TABLE IF EXISTS decsys.kiln_master;
CREATE TABLE `kiln_master` (
`kid` int(7) NOT NULL,
`pattern` varchar(30) NOT NULL,
`item` varchar(30) NOT NULL,
`yeild` double NOT NULL,
`temp` int(6) NOT NULL,
`kiln` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
error
#1442 - Can't update table 'today_plan' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
thank you very much

You're trying to update the row after it has been inserted, isn't it better to do before so that it gets inserted with the correct values? That'd be something like;
CREATE TRIGGER update_yeild BEFORE INSERT ON today_plan
FOR EACH ROW
SET NEW.yeild = COALESCE((SELECT kiln_master.yeild
FROM kiln_master
WHERE NEW.itemno = kiln_master.item
AND NEW.pattern = kiln_master.pattern
LIMIT 1), 0);

Related

MySql Event Scheduler Copy and Insert at Specific Time Every Day

please I need the correct Syntax to Copy and Update A table everyday from another table's MAX row values using MySql's Event Scheduler. The tasks obviously exceeds my basic knowledge of MySql.
This is what I have but its not working:
DELIMITER $$
CREATE
EVENT IF NOT EXISTS `Statement_Opening_Closing_Bal`
ON SCHEDULE EVERY 1 DAY STARTS '00:00:30'
DO BEGIN
-- GET CUSTOMER UNIQUE IDs
SELECT id
FROM customer AS Customer_UniqueIDs;
-- copy associated audit records
SELECT transactiondate, credit, debit, amount FROM passbook.Customer_UniqueIDs WHERE transactionid=MAX(transactionid) AS LastTransactionEachDay;
-- INSERT MAX ROW TRANSACTION FOR ABOVE SELECT INTO StatementofAccountRef.Customer_UniqueIDs,
INSERT INTO StatementofAccountRef.Customer_UniqueIDs (tid, entrydate, dtdebit, dtcredit, dtbalance)
VALUES(NULL, LastTransactionEachDay.entrydate, LastTransactionEachDay.dtdebit, LastTransactionEachDay.dtcredit, LastTransactionEachDay.dtbalance)
END */$$
DELIMITER ;
For clarification, I have a table called Customer with a column named "id" that contains Unique id for all customers.
Now I have several tables with names as Passbook.id (e.g Passbook2, Passbook3, etc...) where "id" in the Column names corresponds to Unique "id" in Table "Customer". Each Passbook.id has Columns named transactiondate, credit, debit, amount.
And I also have several tables with names as StatementofAccountRef.id where "id" in the Column names also corresponds to Unique "id" in Table "Customer". Each StatementofAccountRef.id has Columns named tid, entrydate, dtdebit, dtcredit, dtbalance.
What I want to do is to:
1. Take each "id" from Table Customer and use it to SELECT each customer's passbook.id
Get the Max row values from each passbook.id for Columns "transactiondate", "debit", "credit", "amount". By Max Row values I mean last or most recent row entry in passbook.id as at the time the Event Scheduler runs. This value will be picked at the specific time (00.00.30) everyday whether they change or not as far as they are the most recent entry in table passbook.id
Insert the values into each corresponding StatementofAccountRef.id Column entrydate, dtdebit, dtcredit, dtbalance. "tid" column in StatementofAccountRef.id tables is set to AUTO INCREMENT. entrydate(in StatementofAccountRef.id) is DATETIME as is transactiondate in passbook.id .
Any working help appreciated guys, please. Thanks.
Show Table Data and Sample entries:
Table customer
CREATE TABLE `customer` (
`id` int(5) NOT NULL,
`name` varchar(255) NOT NULL,
`surname` varchar(255) DEFAULT NULL,
`gender` char(1) NOT NULL,
`dob` date NOT NULL,
`nominee` varchar(255) NOT NULL,
`account` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`mobile` varchar(15) NOT NULL,
`email` varchar(255) NOT NULL,
`accessid` varchar(60) NOT NULL,
`password` varchar(255) NOT NULL,
`branch` varchar(255) NOT NULL,
`Branch_Code` varchar(255) NOT NULL,
`lastlogin` datetime NOT NULL,
`accstatus` varchar(255) NOT NULL,
`accnumber` bigint(10) DEFAULT NULL,
`CustomerRefNum` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`CustomerTokenRef` varchar(255) DEFAULT NULL,
`Acc_Manager` varchar(255) DEFAULT NULL,
`currency` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
63, John, Denon, M, 1976-12-10, Jonny Lee, GoldPlus, 200 Monroe Street #233 Rockville MD 2085, cmailultimate#gmail.com, 0458ac7536f4101f597820c7f9136b2354f2f156, Zone C, Team 1, 2018-11-18 03-14-45, Active, 12113, CUDG23299-TYWB02323, Raymond Crow, Dollars
Table passbook63
CREATE TABLE `passbook63` (
`transactionid` int(5) NOT NULL,
`transactiondate` date DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`surname` varchar(255) DEFAULT NULL,
`fullnames` varchar(255) DEFAULT NULL,
`branch` varchar(255) DEFAULT NULL,
`Branch_Code` varchar(255) DEFAULT NULL,
`credit` int(10) DEFAULT NULL,
`debit` int(10) DEFAULT NULL,
`amount` float(10,2) DEFAULT NULL,
`narration` varchar(255) DEFAULT NULL,
`recall_value` varchar(10) DEFAULT NULL,
`transactionRef` varchar(255) DEFAULT NULL,
`transactionreceipts` varchar(255) DEFAULT NULL,
`receiving_Inst` varchar(255) DEFAULT NULL,
`beneficiary_account` varchar(255) DEFAULT NULL,
`beneficiary_name` varchar(255) DEFAULT NULL,
`transaction_datetime` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
Sample Data: 19, 2017-10-15 06:06:06, John, Denon, John Denon, Zone C, Team 1, 6000, 6000, 6000, Double Bet On Customer 101, 0, WERW39489923, Triple Confirmation of Results Reguired, 12113, Harrison Due, 2017-10-19 01:06:06
Table StatementofAccountRef63
CREATE TABLE `StatementofAccountRef63` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`entrydate` datetime DEFAULT NULL,
`dtdebit` int(11) NOT NULL,
`dtcredit` int(11) NOT NULL,
`dtbalance` int(11) NOT NULL,
PRIMARY KEY (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Sample Data: 011, 2018-02-28 06:06:06, 36000, 36000, 96000

MYSQL Trigger Copy Entire Row while insert,update

I have two Table namely admin_user,admin_user_bak
the structure of the table admin_user is
CREATE TABLE IF NOT EXISTS `admin_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(150) NOT NULL,
`name` varchar(150) NOT NULL,
`emailid` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL,
`roll` varchar(50) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`last_login` datetime NOT NULL,
`status` enum('active','inactive') NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and structure of table admin_user_bak have all the fields of admin_user and additionally a field bak_user_id . its auto increment id..
CREATE TABLE IF NOT EXISTS `admin_user_bak` (
`bak_user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`user_name` varchar(150) NOT NULL,
`name` varchar(150) NOT NULL,
`emailid` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL,
`roll` varchar(50) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`last_login` datetime NOT NULL,
`status` enum('active','inactive') NOT NULL,
PRIMARY KEY (`bak_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
here my trigger is
CREATE TRIGGER ins_admin_user BEFORE UPDATE ON admin_user
FOR EACH ROW
BEGIN
INSERT INTO admin_user_bak (user_id,user_name,name,emailid,password,roll,created,modified,last_login,status) VALUES ( NEW.user_id, NEW.user_name, NEW.emailid, new.password, NEW.roll, NEW.created, NEW.modified, NEW.last_login, NEW.status);
END
my purpose is i want to back up all events. insert update delete of a particular record. not all record. i write for insertion. its not working
any idea.. thanks
i want a insertion trigger but you had written update on in your trigger so it's not work.
You use INSERT ON
CREATE TRIGGER ins_admin_user BEFORE INSERT ON admin_user
FOR EACH ROW
BEGIN
INSERT INTO admin_user_bak (user_id,user_name,name,emailid,password,roll,created,modified,last_login,status) VALUES ( old.user_id, old.user_name, old.emailid, old.password, old.roll, old.created, old.modified, old.last_login, old.status);
END

update another table when updated mysql trigger

I have 2 tables, students and Math. I want to UPDATE existing data on Math.Last_name when I update the students.Last_Name using the ID I am updating in students.
Students table
CREATE TABLE `STUDENTS` (
`Date_Modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`LRN` BIGINT(12) NOT NULL AUTO_INCREMENT,
`Last_Name` VARCHAR(50) NOT NULL,
`First_Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`LRN`)
)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=123456789112;
MATH TABLE
CREATE TABLE `Math` (
`Date_Modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`LRN` BIGINT(12) NOT NULL,
`Last_Name` VARCHAR(50) NOT NULL,
`First_Name` VARCHAR(50) NOT NULL,
`Level` VARCHAR(3) NOT NULL,
`UT1` VARCHAR(3) NOT NULL,
`Q1` VARCHAR(50) NULL DEFAULT NULL,
`UT2` VARCHAR(50) NULL DEFAULT NULL,
`Q2` VARCHAR(50) NULL DEFAULT NULL,
`UT3` VARCHAR(50) NULL DEFAULT NULL,
`Q3` VARCHAR(50) NULL DEFAULT NULL,
`UT4` VARCHAR(50) NULL DEFAULT NULL,
`Q4` VARCHAR(50) NULL DEFAULT NULL,
`FINAL GRADE` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`LRN`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT;
MY TRIGGER
CREATE TRIGGER `STUDENTS_after_update` AFTER UPDATE ON `STUDENTS` FOR EACH ROW BEGIN
UPDATE Math
SET Last_Name = NEW.Last_Name
WHERE LRN IN (SELECT LRN FROM Math where LRN = NEW.LRN);
END
You do not need a sub select in the update command, since for each row it will pick up the new LRN value and will update all of them in the MATH table where the new.LRN matches in the MATH table. Here how the trigger would look like
delimiter //
create trigger `STUDENTS_after_update` after update on `STUDENTS`
for each row
begin
update Math
set Last_Name = NEW.Last_Name
where LRN = NEW.LRN ;
end;//
delimiter ;
Note that I have added delimiter which is needed when you run them in the Mysql CLI, some other user interface like PHPMyadmin you need to select the delimiter from the user interface.

MySql - can BEFORE INSERT TRIGGER insert into 2 columns?

Can this trigger be changed so that the sortorder table gets 2 column values (sortOrderId, sortOrder) inserted?
How is the value of sortOrder found?
If it is known and can be inserted into image table then can it also be inserted into the sortorder table?
-- Trigger DDL Statements
DELIMITER $$
USE `nextcart`$$
CREATE
DEFINER=`root`#`localhost`
TRIGGER `nextcart`.`insert_sortorderid`
BEFORE INSERT ON `nextcart`.`image`
FOR EACH ROW
BEGIN
INSERT INTO sortorder SET sortOrderId = NULL, sortOrder = NEW.sortOrder;
SET NEW.sortOrderId = (SELECT LAST_INSERT_ID());
END;
$$
CREATE TABLE sortorder:
delimiter $$
CREATE TABLE `sortorder` (
`sortOrderId` int(11) NOT NULL AUTO_INCREMENT,
`sortOrder` tinyint(4) NOT NULL,
PRIMARY KEY (`sortOrderId`),
KEY `sort_order` (`sortOrderId`,`sortOrder`),
CONSTRAINT `fk_sortOrderId` FOREIGN KEY (`sortOrderId`) REFERENCES `image` (`imageId`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8$$
CREATE TABLE image:
delimiter $$
CREATE TABLE `image` (
`imageId` int(11) NOT NULL AUTO_INCREMENT,
`imageFileName` varchar(45) DEFAULT NULL,
`imagePath` varchar(255) DEFAULT NULL,
`imageTitle` varchar(100) DEFAULT NULL,
`imageAlt` varchar(100) DEFAULT NULL,
`imageWidth` int(11) DEFAULT NULL,
`imageHeight` int(11) DEFAULT NULL,
`classId` int(11) DEFAULT NULL,
`imageSizeId` tinyint(4) NOT NULL,
`isImageEnabled` bit(1) DEFAULT b'0',
`sortOrderId` int(11) DEFAULT NULL,
PRIMARY KEY (`imageId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8$$
ERROR MESSAGE:
Error 1054: Unknown column 'sortOrder' in 'NEW' SQL Statement:
CREATE TRIGGER insert_sortorderid BEFORE INSERT ON image FOR EACH
ROW BEGIN INSERT INTO nextcart.sortorder SET sortOrderId = NULL,
sortOrder = NEW.sortOrder; SET NEW.sortOrderId = ( SELECT
LAST_INSERT_ID()); END; Error when running failback script. Details
follow. Error 1050: Table 'image' already exists SQL Statement: CREATE
TABLE image ( imageId int(11) NOT NULL AUTO_INCREMENT,
imageFileName varchar(45) DEFAULT NULL, imagePath varchar(255)
DEFAULT NULL, imageTitle varchar(100) DEFAULT NULL, imageAlt
varchar(100) DEFAULT NULL, imageWidth int(11) DEFAULT NULL,
imageHeight int(11) DEFAULT NULL, classId int(11) DEFAULT NULL,
imageSizeId tinyint(4) NOT NULL, isImageEnabled bit(1) DEFAULT
b'0', sortOrderId int(11) DEFAULT NULL, PRIMARY KEY (imageId)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
There is no column named sortOrder in the image table.
So, the reference to NEW.sortOrder (on the insert statement in the trigger) is invalid.
To answer your first question: No. Since there is no value supplied for that in the INSERT statement (which fires the BEFORE INSERT TRIGGER), you don't really have a source for that value.
The easy option is to provide a default value for it.
If you want to supply a value for the sortOrder column, then one option is to add a sortOrder column to the image table, and then the value can be supplied in the INSERT INTO image statement. Then it would available in the trigger.
(The purpose of the sortorder table is not at all clear.)

Writing a trigger to update a value with a value from its own row

I have the following table..
CREATE TABLE `community_data_1` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` VARCHAR(1) NOT NULL,
`reply_to_id` BIGINT(20) UNSIGNED NULL DEFAULT NULL,
`subject` TEXT NOT NULL,
`post` MEDIUMTEXT NOT NULL,
`html` VARCHAR(1) NOT NULL DEFAULT '0',
`time_stamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`author_id` BIGINT(20) UNSIGNED NOT NULL,
`d_id` BIGINT(20) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
Now whenever an insert is done, after the insert I need to check if the d_id value is set to zero, if it is then I need to update it to the same value as that of the id of that row. How do I do this?
delimiter |
CREATE TRIGGER fixValue BEFORE INSERT ON community_data_1
FOR EACH ROW BEGIN
IF NEW.d_id = 0 THEN
SET #NewId= (SELECT MAX(id)+1 FROM community_data_1);
SET NEW.d_id = NewId;
END IF;
END;
|
delimiter ;