I have an application where I need to INSERT an auto_increment value from a PK in another table. I know how to do this in PHP, but I need to have this done at the DB level, since I cannot change the program logic.
I am new to triggers, so I'm sure this will be an easy answer for someone. Here is what I have so far:
DELIMITER //
CREATE TRIGGER new_project AFTER INSERT ON m_quality_header
FOR EACH ROW
BEGIN
INSERT INTO m_quality_detail (d_matl_qa_ID) VALUES (NEW.h_matl_qa_ID);
END//
DELIMITER ;
I just want the value of the auto_increment value from h_matl_qa_ID to be inserted as a new record into d_matl_qa_ID. The error I get is:
"This version of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table'
But, I don't want to update the table that has the trigger, so why is my current code considered a 'multiple' trigger?
This is on MySQL 5.0.45-7.el5 running on a CentOS 5 server (64-bit Intel) If I have to, I can modify the PHP code, but that needs to be the last resort.
If you've tried to create the trigger before, as outis states above you can issue the command
SHOW TRIGGERS;
and it will tell you.
If that is the case, what I typically do is issue
DROP TRIGGER IF EXISTS my_trigger_name;
and then recreate the trigger.
Your trigger code, otherwise, looks OK.
DELIMITER //
DROP TRIGGER IF EXISTS new_project//
CREATE TRIGGER new_project AFTER INSERT ON m_quality_header
FOR EACH ROW
BEGIN
INSERT INTO m_quality_detail
(d_matl_qa_ID, d_matl_qa_project_test_number) VALUES (LAST_INSERT_ID(), LAST_INSERT_ID());
END//
DELIMITER ;
Related
I have a table named clients, in that table there's two columns of importance; id and client. I have a secondary table in the same database named calendar. I really want the two columns of id and client in the calendar table to sync with the ones in client table.
Right now I am using this PHP to execute this in MySQL:
INSERT IGNORE INTO calendar (id, client) SELECT id, client FROM clients;
Is there a better way of accomplish this task? Maybe a built in function in MySQL that I have overlooked or something like that?
Use Triggers : The MySQL trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table.
The trigger can be executed when you run one of the following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be invoked before or after the event.
You can make trigger when you insert or update a row in main table and make the changes in another table
Example:
DELIMITER $$
CREATE TRIGGER my_sync_trigger
AFTER INSERT ON `clients` for each row
begin
INSERT INTO calender (id,client)
Values (new.id, new.client);
END$$
DELIMITER ;
"new" stands for the new value inserted into clients table. The same value will be inserted into id and client column in calender.
Note: single quotes are removed from table name because quotes effectively make it a string literal instead of a proper identifier.
DELIMITER command will change the ending of each statement from ";" to "$$" so that MySQL is not confused with ";" inside and outside the trigger
Make similar triggers for update and delete also
Simple guide for examples and syntax:
http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
I am quite new to SQL and am working on a small project, but I got stuck when wanting to implement triggers to my model.
I am designing a database for a sports league. I have a table "GamePlayed" with a column called "GoalsScored" and another one "Team" with a column called "GoalsFor". Those two tables are connected by the "TeamID" key.
I would like to have a trigger that updates the value of "GoalsFor" by adding to the previous value the value of "GoalsScored". In this way, with every game, the total quantity of goals scored will be constantly updated.
I tried the following:
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`
END
Unfortunately, it says there is a problem in my SQL syntax...
How can I do it?
You need to change your delimiter. Something like this
delimiter $$
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`;
END;
$$
See eg http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
I am trying to build a trigger, the problems is it is not working. I have syntax problems. I need to build a trigger which will update a table with another record in the same table before the table has been been updated. The trigger below describes what i want to do but it does not work.
$deletequery = '
DELIMITER //
CREATE TRIGGER after_insert_job_sent
AFTER INSERT
ON Envato_CustomConfig_job_sent FOR EACH ROW
BEGIN
DELETE FROM `Envato_CustomConfig_Job_Queue`
WHERE Job_ID = '.$value['Job_ID'].'
AND email -'.$value['email'].';
UPDATE `envato_customconfig_job_status` SET `email_Sent_Count`= email_Sent_Count+1
WHERE Job_ID = '.$value['Job_ID'].'
END; //
DELIMITER;
insert into Envato_CustomConfig_job_sent
values ( NULL , '.$value['Job_ID'].', '.$value['email'].', now();
';
EDIT:
Why does my query append other records aswell?....
so basically it is working however on the update is add one to the last record the db. i have tried LIMIT it did not work. any ideas.
insert into Envato_CustomConfig_job_sent
values ( NULL , '37', 'email', now());
DELETE FROM Envato_CustomConfig_job_queue
WHERE Job_ID = '37'
AND email ='email';
UPDATE envato_customconfig_job_status SET `email_Sent_Count`= email_Sent_Count+1
WHERE Job_ID = '37';
Triggers, Events, Functions, and Stored Procedures reside as code stored in a particular database. Only some of them have parameter passing (such as Functions and Stored Procedures). Others just fire are their own (Events and Triggers).
What you are attempting to do is perform a delete with PHP variable information which is just a query.
At least you have the DELIMITER concept nailed down, that stands in the way as a trivial error that catches many people. But if you would have highlighted the Trigger block, you would have seen the syntax error highlighting, most likely, around the embedded WHERE Job_ID = '.$value['Job_ID'].' chunk. And since the trigger runs on triggered events such as insert, etc, it would have no clue about that chunk.
When I say highlighted, I mean in a program such as Mysql Workbench.
I am using PHP MyAdmin Version 4.1.12.
I am trying to create a simple trigger that, after an update, sets 'dateModified' in table 'person' to CURRENT_TIMESTAMP. dateModified is of type TIMESTAMP. The way in which the update occurs to person is the setting of a single attribute in a single record through a X-Editable enabled grid view on a web page. After performing validation against the model with the updated attribute, a new database command is created with the relevant update SQL and executed. So each update only ever modifies a single row within 'person'.
Here is the SQL I wrote to create the trigger:
DELIMITER |
CREATE TRIGGER PERSON_AUPD AFTER UPDATE ON person
FOR EACH ROW BEGIN
SET #dateModified = CURRENT_TIMESTAMP ;
END;
|
DELIMITER ;
After performing updates, I see that the trigger hasn't fired, and the timestamp remains unchanged from the one they were created with (the default for dateModified, and dateCreated, are both CURRENT_TIMESTAMP, so they get set automatically on insert).
I have looked around for answers, and even looked into alternate methods to getting the update (the alternate method was calling a model's afterupdate method and performing separate SQL there on dateModified). I would prefer to exhaust every opportunity to use the triggers, before I go putting more code into my model.
Any help would be greatly appreciated.
Thanks to #juergend, the solution was the following:
Set trigger type to before update because after update cannot update attributes, and are best used to insert new records in related audit tables, etc.
Add NEW. to the front of the attribute you wish to modify.
I have a mysql database with 12,000 entries, what i want setup is the ability to monitor a column in the database and if/when the column is altered for any entry it sends me an email with the details.
EDIT: I have access to mysql db, but not the script which works with it. So it should monitor it for changes...
You could create some triggers on the table, if your version of MySQL has them. A trigger can then invoke any function you care to create. A trigger has the advantage that any insertion or deletion or any update of the column will cause it to fire; you wouldn't have to change any other code to make it happen. See here for more... http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Create a trigger on update
Create another table (lets call it cron_table), where the trigger will insert information of the updated row (may be old value, new value etc)
Setup a cron, which will call a script which will check the cron_table and send email if any entry is found. Cron interval can be setup according to need.
--- If you could send email from trigger, there would be no need for a separate table and cron ---
try something similar to this , you can edit the function to send you and email if the query has insert and TABLE_NAME or COLUMN_NAME in it
set up one column to be a datetimestamp.
This will update on every change of the row. There you can run a sql query either via a cron job or after every few php queries to return you the list of changed rows since the last check.
Select * from tbl_myentries where EntryUpdated > '$TimeSinceLastCheck'
you need to understand Data Manipulation Language (DML) triggers
in my sql: use
CREATE TRIGGER salary_trigger
BEFORE UPDATE ON table_name
REFERENCING NEW ROW AS n, OLD ROW AS o
FOR EACH ROW
IF n.columnName <> o.columnname THEN
END IF;
;
Create a trigger on a change on your column, then insert it to another table as log table.
Run cron job on your table that will send you an email.