Truncate table in mysql - mysql

I want to make trigger and this is code
DELIMITER $$
CREATE TRIGGER tax_year_update AFTER UPDATE ON const_data
FOR EACH ROW
BEGIN
IF NEW.tax_year <> OLD.tax_year THEN
TRUNCATE family_income;
TRUNCATE student_income;
END IF;
END$$
DELIMITER;
It causes this error
1422 - Explicit or implicit commit is not allowed in stored function or trigger.
Any suggestions why it doesn't work?

Truncate implicitly commits the transaction which is not allowed inside the trigger. Also TRUNCATE TABLE is DDL statament. You need to better use DELETE instead of TRUNCATE.
From the source:
Depending on version and storage engine, TRUNCATE can cause the table
to be dropped and recreated. This provides a much more efficient way
of deleting all rows from a table, but it does perform an implicit
COMMIT. You might want to use DELETE instead of TRUNCATE.
So you can try
DELETE FROM family_income;
DELETE FROM student_income;
instead of
TRUNCATE family_income;
TRUNCATE student_income;

While you truncating the table and if it records relates to other tables. It won't be truncating.
For that first you've to remove all the records from table in which you want to truncate.
Then go to options and set auto-increment with 1.
Enjoy :)

Related

Drop a trigger from within the trigger body

I want to run a trigger once and only once the first time a condition is satisfied.
To do this I would like to drop the trigger from within the body of the trigger itself. I have two questions: 1) is there a better way than this and 2) will anything weird happen if I drop the trigger inside the trigger body?
This is what I have so far. For context: There's another process running moving things to done and in a particular case it does not write the result so in that case I want to run a script such that when they're all done I want this trigger to read some values another table and then remove the trigger itself so that it doesn't run every single time stuff gets done normally.
CREATE TRIGGER some_trigger AFTER UPDATE ON table_name FOR EACH ROW
SELECT CASE WHEN ((SELECT count(*) FROM table_name WHERE status!='done') = 0)
THEN BEGIN
UPDATE table_name SET result = (SELECT other.result FROM table_name, other WHERE other.id = table_name.id);
DROP TRIGGER some_trigger;
END;
ELSE BEGIN END;
END CASE;
EDIT: also a third question, what does "FOR EACH ROW" mean? I only want the trigger to run once, not once per row. Looking at the docs it seems like "FOR EACH ROW" is not optional.
DROP TRIGGER cannot be performed within a Trigger.
To explain why, firstly, DROP TRIGGER causes an implicit commit, and secondly, commits cannot occur within triggers. Details below:
DROP TRIGGER causes an implicit commit
See (https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html):
The statements listed in this section (and any synonyms for them) implicitly end any transaction active in the current session, as if you had done a COMMIT before executing the statement.
...
Data definition language (DDL) statements that define or modify database objects. ALTER EVENT, ALTER FUNCTION, ALTER PROCEDURE, ALTER SERVER, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE EVENT, CREATE FUNCTION, CREATE INDEX, CREATE PROCEDURE, CREATE ROLE, CREATE SERVER, CREATE SPATIAL REFERENCE SYSTEM, CREATE TABLE, CREATE TRIGGER, CREATE VIEW, DROP DATABASE, DROP EVENT, DROP FUNCTION, DROP INDEX, DROP PROCEDURE, DROP ROLE, DROP SERVER, DROP SPATIAL REFERENCE SYSTEM, DROP TABLE, DROP TRIGGER, DROP VIEW, INSTALL PLUGIN, RENAME TABLE, TRUNCATE TABLE, UNINSTALL PLUGIN.
Commits cannot occur within a trigger:
See (https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html):
The trigger cannot use statements that explicitly or implicitly begin or end a transaction, such as START TRANSACTION, COMMIT, or ROLLBACK. (ROLLBACK to SAVEPOINT is permitted because it does not end a transaction.).

How to rollback all statements inside a MySQL Transaction?

I need to update a specific column of a table (bigtable) containing ids of another table (FK constraint to oldsmalltable) to point to ids on another table (FK constraint to newsmalltable). Basically this is what I am doing:
DELIMITER //
CREATE PROCEDURE updatebigtable ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING ROLLBACK;
START TRANSACTION;
ALTER TABLE bigtable DROP FOREIGN KEY bigtable_ibfk_1,
MODIFY smalltable_id SMALLINT ;
UPDATE bigtable SET smalltable_id=CASE smalltable_id
WHEN 1 THEN 1592
WHEN 2 THEN 1593
WHEN 3 THEN 1602
...
ELSE 0
END;
ALTER TABLE bigtable ADD CONSTRAINT bigtable_ibfk_1
FOREIGN KEY(smalltable_id) REFERENCES newsmalltable(id);
COMMIT;
END//
DELIMITER ;
CALL updatebigtable();
DROP PROCEDURE updatebigtable;
I need to ensure that if by some reason the new Foreign Key constraint fails (e.g. with columns with different types, the error would occur on the last alter table statement), the UPDATE and the first ALTER TABLE should be rolled back as well, i.e. they should remain as they were initially.
According to MySQL documentation, by using START TRANSACTION the autocommit mode is disabled for that transaction, which will not allow:
that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent.
I only found this question as minimally related to mine:
How can I use transactions in my MySQL stored procedure?
If that error I mentioned occurs inside the transaction, the previous statements were already executed and the updates were "permanently done on disk"...
I also tried to place SET autocommit=0; before creating the procedure but the behavior is still the same... Am I missing something? Or is this the expected behavior of a MySQL transaction rollback?
If it makes any difference, I am using MySQL v.5.6.17.
ALTER TABLE statements always cause an implicit commit (section 13.3.3 from MySQL docs, thanks wchiquito), which means that even if they're inside a START TRANSACTION; ... COMMIT; block, there will be as many commits as the number of alters done inside that block.
Locking the table is not an option as well since (from problems with ALTER TABLE):
If you use ALTER TABLE on a transactional table or if you are using Windows, ALTER TABLE unlocks the table if you had done a LOCK TABLE on it. This is done because InnoDB and these operating systems cannot drop a table that is in use.
The only option left for avoiding unwanted reads/writes while the alter and update statements are being executed is emulating all the steps of an ALTER TABLE:
Create a new table named A-xxx with the requested structural changes.
Copy all rows from the original table to A-xxx.
Rename the original table to B-xxx.
Rename A-xxx to your original table name.
Delete B-xxx.
This way the updates can be done in the new table (after step 2) and the only time the bigtable is unavailable is while doing step 3 and 4 (renaming).
Use a TRY CATCH block
BEGIN TRAN before BEGIN TRY and ROLLBACK TRAN inside CATCH block

What is the right way to modify a MySQL trigger?

As you probably know, there's no syntax that modifies a MySQL trigger.
To do that, you need to execute DROP TRIGGER and then re-create it again with the new definition.
What is the right/best way of doing this, considering the following:
You cannot encapsulate these two statements in a transaction as that will be pointless (both DROP TRIGGER and CREATE TRIGGER invoke implicit transactions)
You cannot use LOCK TABLES READ as an error is triggered
Just between your DROP and CREATE TRIGGER, some other session might insert/update/delete row(s) which won't be handled by neither of your new nor old triggers.
When testing before I posted, I overlooked what type of LOCK I'm acquiring, it was READ.
So it seems using WRITE lock does the job:
delimiter $$
LOCK TABLES table1 WRITE $$
DROP TRIGGER IF EXISTS after_insert_on_table1 $$
CREATE TRIGGER after_insert_on_table1 AFTER INSERT ON table1
FOR EACH ROW
BEGIN
...
END
$$
UNLOCK TABLES $$
delimiter ;
So my recommendation is to always use this sequence when updating/modifying triggers.

How to sync values in a table column in mysql trigger

I need to sync values in a table column in mysql trigger while having the same value in another column. Here is an example of my table:
id___MP____sweek
1____2_____1
2____2_____1
3____1_____2
4____1_____2
5____3_____3
6____3_____3
If a user changes, for example, MP in the first row (id=1) from 2 to 4, then the value of MP with the same sweek has to be changed (e.g., id=2, MP becomes also 4).
I wrote a BEFORE UPDATE tigger that does not work:
USE moodle;
DELIMITER $$
CREATE TRIGGER trigger_course_minpostUPD BEFORE UPDATE ON moodle.mdl_course_sections FOR EACH ROW
BEGIN
IF NEW.MP <> OLD.MP THEN
BEGIN
SET #A=NEW.MP;
SET NEW.MP = #A
WHERE OLD.sweek=NEW.sweek;
END;
END IF;
END$$
DELIMITER ;
From within a MySQL trigger you are not able to affect other rows on the same table.
You would want to say something like:
UPDATE my_table SET MP=NEW.MP WHERE sweek = NEW.sweek
But - sorry - no go.
There are hack around this -- and ugly ones, too.
If your table is MyISAM, you can wrap it up with a MERGE table, and act on the MERGE table instead (MySQL doesn't realize at that point you're actually hacking around it).
However, using MyISAM as a storage engine may not be a good thing -- today's focus is on InnoDB, a much more sophisticated engine.
Another trick is to try and use the FEDERATED engine. See relevant post by Roland Bouman. Again, this is a dirty hack.
I would probably let the application do the thing within the same transaction.

MySQL trigger which triggers on either INSERT or UPDATE?

Is there a way to create MySQL trigger which triggers on either UPDATE or INSERT?
Something like
CREATE TRIGGER t_apps_affected BEFORE INSERT OR UPDATE ...
Obviously, the above don't work. So, any workarounds without creating two separate triggers?
I need this in order to update running counter on another table.
Unfortunately, there is no shorthand form - you must create multiple triggers - one for each event.
The doc says:
trigger_event indicates the kind of statement that activates the trigger. The trigger_event can be one of the following:
INSERT: The trigger is activated whenever a new row is inserted into
the table; for example, through INSERT, LOAD DATA, and REPLACE
statements.
UPDATE: The trigger is activated whenever a row is modified; for
example, through UPDATE statements.
DELETE: The trigger is activated whenever a row is deleted from the
table; for example, through DELETE and REPLACE statements. However,
DROP TABLE and TRUNCATE TABLE statements on the table do not activate
this trigger, because they do not use DELETE. Dropping a partition
does not activate DELETE triggers, either. See Section 12.1.27,
“TRUNCATE TABLE Syntax”.
While it is impossible to put a trigger on multiple events, you can define the two triggers to merely call another stored procedure and, with that, cut down on the amount of code you need to commit. Just create the separate triggers to do nothing but, say,
CALL update_counter();
and put all of your actual work into the procedure. The triggers would then be a simple
CREATE TRIGGER t_apps_affected BEFORE INSERT ON table
FOR EACH ROW
BEGIN
CALL update_counter();
END;