using trigger to update another database's table on same server - mysql

I am trying to insert record in db2.inventory whenever there is an insert event in db1.sales using triggers.
DROP TRIGGER IF EXISTS `insertintodb2`;
CREATE DEFINER=`root`#`localhost`
TRIGGER `insertintodb2` AFTER INSERT ON `sales`
FOR EACH ROW
INSERT INTO `db2.dbo.inventory` (ID) VALUES (0);
it is giving me error
db1.db2.dbo.inventory doesn't exist.
how can i make this work.
thank you

As you can see here quotes (backtick) are used to identify objects names, but you must use them on every single object:
`db2`.`dbo`.`inventory`
or without them if object names are not misleading:
db2.dbo.inventory

MySQL and MariaDB do not use the .dbo. syntax. There is only database (aka schema) name and table name:
db2.inventory
or
`db2`.`inventory`
(The presence or absence of backtics does not matter in this situation.)

Related

MySQL: How to pass parameter to a trigger

I have a table on a mysql 5.7 db, containing say athletes with their mean, max, avg times in a specific sport. I have another table that lists some calculated statistics based on those values.
I managed to do the calculcations that end up on the second using stored procedures. I use as input parameter to the stored procedure the athlete's name.
So when in the first table, an athlete is inserted (with his/her avg/min/max times) or his/her values are updated and I run the stored procedure, the later updates the statistics table.
My question is how to achieve the same result with triggers?
I guess it is feasible/easy to update the entire table on each insert or update of the first table. What would be more efficient performance-wise, would be on each :
INSERT into table1 values (..) where athlete_name="John Do"
(...)
ON DUPLICATE KEY UPDATE (...)
Run a trigger in the pseudocode form :
INSERT into statistics_table values (..) where athlete_name="John Do"
ON DUPLICATE KEY UPDATE (...)
How can the the athlete_name="John Do" be passed to the trigger dynamically, to avoid update the entire statistics table?
You cannot pass any parameters to a trigger and the insert statement does not support the where clause either.
Having said this, a trigger can pick up the user's name from the record being inserted / updated / deleted using NEW.athlete_name or OLD.athlete_name (whichever is required) and use that to call a stored procedure:
Within the trigger body, the OLD and NEW keywords enable you to access
columns in the rows affected by a trigger. OLD and NEW are MySQL
extensions to triggers; they are not case-sensitive.
In an INSERT trigger, only NEW.col_name can be used; there is no old
row. In a DELETE trigger, only OLD.col_name can be used; there is no
new row. In an UPDATE trigger, you can use OLD.col_name to refer to
the columns of a row before it is updated and NEW.col_name to refer to
the columns of the row after it is updated.
A column named with OLD is read only. You can refer to it (if you have
the SELECT privilege), but not modify it. You can refer to a column
named with NEW if you have the SELECT privilege for it. In a BEFORE
trigger, you can also change its value with SET NEW.col_name = value
if you have the UPDATE privilege for it. This means you can use a
trigger to modify the values to be inserted into a new row or used to
update a row. (Such a SET statement has no effect in an AFTER trigger
because the row change will have already occurred.)
You can create triggers that fire after each insert or update on the parent table (athletes). Within each trigger, you can access the value of column athlete_name on the record that was just created or changed, and then invoke your stored procedure using CALL().
Here is a code sample for such an INSERT trigger :
CREATE TRIGGER athletes_upd AFTER INSERT ON athletes
FOR EACH ROW
BEGIN
CALL my_procedure(NEW.athlete_name);
END;
UPDATE trigger :
CREATE TRIGGER athletes_upd AFTER UPDATE ON athletes
FOR EACH ROW
BEGIN
CALL my_procedure(NEW.athlete_name); -- or maybe OLD.athlete_name ?
END;

How to use multiple events in one sql trigger?

This is my code at the moment:
DROP TRIGGER `backup`;
DELIMITER $$
CREATE TRIGGER `backup` AFTER INSERT UPDATE DELETE
ON `warehouse`
FOR EACH ROW
BEGIN
END$$
DELIMITER ;
This is the error I keep getting:
I checked my version of MariaDB. It's 10.1.21
It works if I use only one event, but with two or three it throws this error.
Insert Update trigger how to determine if insert or update
In MySQL or MariaDB, each trigger must be defined for exactly one event. You cannot define a trigger that will work for multiple events.
https://dev.mysql.com/doc/refman/5.7/en/create-trigger.html has the syntax:
trigger_event: { INSERT | UPDATE | DELETE }
This syntax notation means the event must be one of the three values INSERT, UPDATE, or DELETE.
Another clue is found if we DESCRIBE INFORMATION_SCHEMA.TRIGGERS:
EVENT_MANIPULATION enum('INSERT','UPDATE','DELETE')
The event type is an enum which means it can only have one value, not multiple.
The example you linked to is for Microsoft SQL Server, not MySQL or MariaDB.
Despite the fact that both "Microsoft" and "MySQL" start with a similar syllable, these are two different products, with different features.

Can you modify a foreign key on insert with a trigger?

I have an issue where a query is inserting into table A, which references table B, but it's using the wrong foreign key for table B. Is it possible to create a trigger in oracle where if the input foreign key is 'ASDF', we modify it to 'FDSA' before the insert so that we can fix this issue?
In either MySQL or Oracle, you can do this using a before insert trigger.
I don't recommend using a trigger for this purpose. Fixing the input data or adding the new value to the reference table seem to me to be more sensible approaches.
Following up on #GordonLinoff's post - I agree with (what appears to be) his point that a trigger is inappropriate here. However, recognizing that sometimes you have to work with what you're given, if you were to use a trigger you'd use a BEFORE INSERT trigger, as in:
CREATE TRIGGER TABLE_A_BI
BEFORE INSERT ON TABLE_A
FOR EACH ROW
BEGIN
IF :NEW.FK_FIELD = 'ASDF' THEN
:NEW.FK_FIELD = 'FDSA';
END IF;
END YOUR_TABLE_BI;
Best of luck.

Trigger on Update of a specific field in mySQL

I am trying to replicate the Username field in my database. Specifically I was looking to add/remove the Username across different tables, whenever the row that contains Username is added inside UserDatabase. To that end, I was thinking of using the trigger mechanism.
I am thinking along the lines of:
CREATE TRIGGER 'addUsername' AFTER INSERT ON UserDatabase FOR EACH ROW
IF (UPDATE(Username))
BEGIN
INSERT INTO anothertable (Username) VALUES ('NewUser');
END
My question is that is how do I capture the updated Username from UserDatabase and replicate it into NewUser? And also, is there a way to remove FOR EACH ROW as I only want the loop to run once?
Thanks!
From the manual:
Within the trigger body, you can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.
And no, you can not remove for each row and I think you misunderstood it a little. There actually is no loop. for each row refers to multiple rows in your insert or update statement. When you add multiple users with one insert statement, you want all of them replicated, right? Not just one.
Then you should note, that there's a difference between single-quotes and backticks. Backticks should be used, if a column or tablename or whatever includes characters that shouldn't be there, like a space, or if the name is actually a reserved keyword. Single-quotes, like you used them for the trigger name are used to tell MySQL it's a string.
Your trigger should look something like this:
CREATE TRIGGER 'addUsername' AFTER INSERT ON UserDatabase
FOR EACH ROW
INSERT INTO anothertable (Username) VALUES (NEW.Username);
For an update statement, you have to create another trigger.

SQL server 2008 trigger before insert

I am very new to SQL and sorry for asking this is very primary knowledge. My issue as follow.
I have a table called Group and minimumVal and maximumVal are two columns. minimumVal always should be less than maximumVal. I want to check this before inserting a new record to the table. If this condition failed data should not inserted into the DB.
So as per my understanding I though of having a trigger but have no idea how to write this.
This is what I write so far;
CREATE TRIGGER tr_Group
ON Table_Group
for INSERT
AS
????
Please advise me.
I recommend you use check constraints for this:
ALTER TABLE dbo.Table_Group ADD CONSTRAINT CK_Group
CHECK (minimumVal < maximumVal)
If you still want to use triggers, then you need an INSTEAD OF trigger:
CREATE TRIGGER tr_Group ON Table_Group
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Table_Group
SELECT *
FROM INSERTED
WHERE minimumVal < maximumVal
END