MySql - trigger doesn't run as expected - mysql

New to MySql triggers, just learning.
CREATE TRIGGER MyTrigger
AFTER UPDATE ON MyTable
FOR EACH ROW
BEGIN
IF (new.field1 < 0 or new.field1 > 5) THEN
UPDATE new SET new.field1 = old.field1;
END IF;
END;
The goal is to keep the value of field1 the same, if the update puts it outside the range.
However, instead it sets it to 0. What am I doing wrong? How should this code look?

Here is an example that should hopefully get you started:
DELIMITER ~
CREATE TRIGGER `so_13547992_trigger`
BEFORE UPDATE ON `so_13547992`
FOR EACH ROW BEGIN
IF ( NEW.`field1` < 0 OR NEW.`field1` > 5 ) THEN
SET NEW.`field1` = OLD.`field1`;
END IF;
END;
~
Why would it work better? Well first of all your example trigger is recursive, you can't update the same table in a trigger that was triggered by an update.
Second, the new in your UPDATE statement is not a table name, you need to specify one explicitly.
It doesn't appear to be a legit trigger at all, doesn't your server complain when you try to create it? Can you perhaps show actually SHOW CREATE TRIGGER `your_trigger`; to make sure that it's really created and looks like you pasted it above?
Even if your example would would work, you're trying to do an unconstrained update on all rows of your table, not on the ones you're trying to update, you should have a WHERE clause; again, given that issue one and two are taken care of.

Related

Adding comments/notes

I have a trigger as follows:
DELIMITER //
create trigger highStockInsert
After insert on inventory
for each row Begin
if new.currentStock > 250 then Insert INTO higherStockList VALUES (new.prodName, new.StockCount, new.storeName, 'High Alert');
end if; end
// ;
Now when this trigger is act upon I would like mysql to give a message of some sorts, I was messing around with SQLSTATE but if this is triggered the table doesn't update it just blocks the whole insert statement from going through. I was wondering if its possible for the new row to be added but still give off a notification. I was looking if its possible to trigger a warning but found no luck either.
Thanks!

SQL where syntax error with trigger

create trigger cal_retweet before insert on T
for each row begin
set NEW.retweet_change = NEW.retweet_count - retweet_count where id_str = NEW.id_str
end
SQL said there is syntax error near "where id_str = NEW.id_str"
My table looks like this. Where id_str is a unique identifier for a specific tweet. Since I am inserting 50 tweets from a single user every minute, there would be many same id_str. What I want to look at is the change of retweet_count every minute. tweeted_at is when the user tweeted, created_at is when this data is inserted into my database. I want to generate retweet_change for each new data inserted into the database compared to the same old tweet (into the column retweet_change). How should I write the trigger?
After reading some of your comments I changed my code to :
create trigger cal_retweet before update on T
for each row
begin
set NEW.retweet_change = NEW.retweet_count - OLD.retweet_count;
end;
There is still syntax error
There are several issues with this trigger.
You have some syntax errors. You need proper semicolons to delimit your statements.
You have a WHERE statement that is out of place (and actually not needed). You are acting on only a single row at a time, you don't have to match on the id_str.
In order to factor in a calculation using an existing value from the row, you need access to the OLD keyword. For that, you need a trigger that happens on UPDATE, not INSERT. On INSERT, the retweet_change is simply the same as retweet_count; you could alter your INSERT statement to fix that problem.
You may need to explicitly add a statement delimiter as per the comments below.
So all together, I think this trigger should look like:
DELIMITER //
CREATE TRIGGER cal_retweet BEFORE UPDATE ON T
FOR EACH ROW
BEGIN
SET NEW.retweet_change = NEW.retweet_count - OLD.retweet_count;
END;//
DELIMITER ;

how to use the msql trigger to update a column

As illustrated in the image below, I want the column grand_score to be automatically calculated when values for paper_score and final_score are inserted.
This is what i have tried:
DELIMITER $$
CREATE TRIGGER myTableAutoSum
BEFORE INSERT ON `stumgr_scores` FOR EACH ROW
BEGIN
SET NEW.grand_score= NEW.paper_score + NEW.final_score;
END;
$$
DELIMITER ;
Issue
when i input values for paper_score and final_score, the table does not get updated (i mean grand_score)
Image
I don't immediately see what is wrong with your trigger, unless one of the values happens to be NULL. That is easily fixed using COALESCE():
SET NEW.grand_score = COALESCE(NEW.paper_score, 0) + COALESCE(NEW.final_score, 0);
I question the use of triggers for this purpose. You also need a trigger for UPDATE, in case the values change that way.
Isn't simpler to remove grand_total from the table and use a view?
create view v_stumgr_scores as
select ss.*,
COALESCE(ss.paper_score, 0) + COALESCE(ss.final_score, 0) as grand_score
from stumgr_scores ss;
Or, better yet, in the most recent versions of MySQL, just use a generated column. That is the best solution -- it even allows you to create an index on the value.

MySQL Trigger before update - set dateformat from string

i have a site where i can update the date of a row, by clicking on the table, when i change the value and press enter its updated in the database.
what i want: in the date field. just to type mm/dd (e.g. 05-20) press enter.
then my trigger should:
CREATE TRIGGER before_transactions_update
BEFORE UPDATE
ON Transactions FOR EACH ROW
BEGIN
-- variable declarations
declare inputDate integer;
-- trigger code
-- get month and day
-- LEFT(inputDate, 2); RIGHT(inputDate, 2)
-- STR_TO_DATE('2015,MONTH(LEFT),DAY(RIGHT)','%Y,%m,%d');
SET INSERTED.date = 2015-month-day-00-00-00;
END;
this is what i've "tried" or at least as far as i have come on my own. MySQL workbench stops me at the declaration of my var, it tells me i need a semi colon after declaration, which i dont seem to need
So i've been googling for hours and i've met a dead end as a newbie in MySQL so could anyone fill out the blanks or point me in the right direction,
that would be great
You can not pass the input parameter directly into the trigger unless that input is somewhere in the update statement
Also you need to specify a delimiter in the trigger.
If your input values are always in the form m-d as you shown in the example and the year is the current year then the following trigger should do the job.
delimiter //
CREATE TRIGGER before_transactions_update BEFORE UPDATE
ON Transactions
FOR EACH ROW
BEGIN
if length(new.date) = 5 then
set new.date = concat(year(curdate()),'-',new.date);
end if ;
END;//
delimiter ;

update trigger to maintain correct url in field

I am seeking a short term solution while I work out why a synchronisation is setting one field wrong in a table
I prepared a trigger and would welcome some comment on it, and any necessary corrections or better strategies.
CREATE TRIGGER urlcorrect AFTER INSERT ON sym_node
FOR EACH ROW BEGIN
IF NEW.sync_url= 'http://wrongaddress' THEN
UPDATE sym_node SET sync_url= "http://123.456.7.89:1234/etc";
END IF;;
END$
delimiter;
thanks
David
Your trigger is wrong in various ways.
First of all, I think you want a BEFORE trigger so that you can fix the row before it gets into your table.
Secondly, this:
UPDATE sym_node SET sync_url= "http://123.456.7.89:1234/etc";
would update every sync_url in the sym_node table and that's not what you want. And I don't think MySQL will let you UPDATE a table inside a trigger on that table (someone correct me if I'm wrong on this please). Also, you should be using single quotes for string literals even though MySQL will let you use double quotes, don't pick up bad habits from MySQL lax behavior. You want to:
set new.sync_url = 'http://123.456.7.89:1234/etc';
Putting all that together, you get this:
delimiter $
create trigger urlcorrect before insert on sym_node
for each row begin
if new.sync_url = 'http://wrongaddress' then
set new.sync_url = 'http://123.456.7.89:1234/etc';
end if;
end;
$
delimiter ;