MySQL trigger with 2 queries - sql

I want to make a trigger to a certain table that makes it so that when I insert data into that table, two other tables are updated. I am trying to do something like this, on the trigger section of phpMyAdmin:
INSERT INTO db.tableOne (id, name, country) VALUES (NEW.id, NEW.name, NEW.country);
INSERT INTO db.tableTwo (id, colour, price) VALUES (NEW.id, NEW.colour, NEW.price);
It gives me a syntax error.
I tried creating 2 different triggers for the same action on that table but it says that I can't have 2 triggers for the same action. Any help is deeply appreciated!

Ok, solved. For anyone who has the same problem, it's quite easy actually: just put a "BEGIN" statement before the "INSERT" statements, and a "END" statement after.

Related

SQL Statement Error table to table

Trying insert table data into another table,
But I'm getting the following error:
Msg 2627, Level 14, State 1, Line 4
Violation of PRIMARY KEY constraint 'PK___4__10'. Cannot insert duplicate key in object 'dbo.tbl_Diagnosis_Table'.
Appears to be a duplicate primary key between both tables. Both tables have the same fields and data types, different data. What query can resolve this issue?
INSERT INTO tbl_Diagnosis_Table
SELECT *
FROM tbl_Holding_Diagnosis_Table
INSERT INTO tbl_Diagnosis_Table(Code, [Description], Comments, Discontinued)
(SELECT
Code, [Description], Comments, Discontinued
FROM
tbl_Holding_Diagnosis_Table);
Assuming Code is the primary key this should eliminate the duplicate rows from the insert:
INSERT INTO tbl_Diagnosis_Table (Code, [Description], Comments, Discontinued)
SELECT Code, [Description], Comments, Discontinued
FROM tbl_Holding_Diagnosis_Table
WHERE tbl_Holding_Diagnosis_Table.Code NOT IN
(SELECT Code FROM tbl_Diagnosis_Table)
If the primary key is some other column, or a composite key, you might need to use a join instead.
You might want to look at the MERGE statement if you want to update existing rows and only insert new.
You need a WHERE with an IN Clause To filter the records to insert, but first you need to know wich fields form the primary key.
If what you're saying is correct i.e. all the values are unique, it leaves only one option. Make sure that if there is an identity column in table tbl_diagnosis_table, you are setting the IDENTITY_INSERT to ON on this table and providing values manually in the select. It might have been possible that the seed and increment was reset in the past. In case you were wrong, you have to use a where clause as suggested by others.
I was going to suggest using a Merge query to do insert or update until I noticed the two inserts in the sample code both do the same insert. The error also says the error is on line 4 which is where the second insert occurs. If the two inserts aren't two examples of the problematic code, then the resolution may be as simple as removing one of the inserts.
Otherwise the other answers are correct, the duplicate rows need to be filtered and the IDENTITY_INSERT has to be turned on for the table.
SET IDENTITY_INSERT tbl_Diagnosis_Table ON -- if it is necessary to have the same primary key
MERGE tbl_Diagnosis_Table AS target
USING (SELECT Code, Description, Comments, Discontinued FROM tbl_Holding_Diagnosis_Table) AS source (Code, Description, Comments, Discontinued)
ON (target.Code = source.Code)
WHEN MATCHED THEN
UPDATE SET Description = source.Description,
Comments = source.Comments,
Discontinued = source.Discontinued
WHEN NOT MATCHED THEN
INSERT (Code, Description, Comments, Discontinued)
VALUES (source.Code, source.Description, source.Comments, source.Discontinued)
END; -- missing semicolons causes errors
SET IDENTITY_INSERT tbl_Diagnosis_Table OFF
Do your homework though. There are some very good reasons not to use Merge.
Use Caution with SQL Server's MERGE Statement
Indexed views and Merge
Optimizing Merge Statement Performance

Sqlite: is it possible to iterate select results in sql?

I have problem. I need trigger after insert. But trigger have to insert few rows depends on select from other table.
is it possibe in sql?
Update:
ok, sorry.
Example (no-logic)
tables:
users(id,name,type_user)
type_user(id,type)
items(id,name,type_user) - some type of users can posses only few items users_items(id,item_id,user_id)
And when i insert into users i want to insert into users_items all items which user can posses
Yes it is possible. Inside SQL Triggers you can do Insert statements.
You can find SQL Trigger information
here.
Try something like
CREATE TRIGGER RelateItems
ON User
AFTER INSERT
AS
--INSERT STATEMENT HERE - INSERT INTO users_items
GO

Oracle SQL Trigger insert/update

Ok so my question should be an easy one i think.
I am just learning Triggers, and I am trying to figure out a homework question.
I have three tables,
Movies (title, year, length, genre, studioName, producer)
StarsIn (movieTitle, starName)
MovieStar (name, address, gender, birthdate)
So basically i need to write a trigger for assuring that at all times, any star appearing in StarsIn also appears in MovieStar. I need to make the trigger for both insert and update events.
UPDATE:
Ok so i changed my statement a little but i still can't figure this out
CREATE OR REPLACE TRIGGER movieTrigger
AFTER UPDATE OR INSERT ON STARSIN
FOR EACH ROW
WHEN(new.STARNAME NOT IN(SELECT "NAME" FROM MOVIESTAR))
BEGIN
INSERT INTO MOVIESTAR("NAME")
VALUES(new.STARNAME)
END;
Now I am getting the error
Error report:
ORA-02251: subquery not allowed here
02251. 00000 - "subquery not allowed here"
*Cause: Subquery is not allowed here in the statement.
*Action: Remove the subquery from the statement.
I just learned that oracle does not support a subquery in the when clause...
So i am trying to figure this out with limited knowledge. But if anyone has a clever way of doing this i would really like to know :-).
Thanks again
You created a statement-level trigger. It will fire once for each insert or update statement. But a single insert or update statement can insert/update many rows in one go. Your code however needs a single row and assumes that only a single row is inserted or updated.
What you need are rowlevel triggers ("FOR EACH ROW") if you want to follow this path.
Your trigger should be fired before(in this case) the insert of any row (currently it fires once for multiple rows inserted once)
I would recommend reading http://docs.oracle.com/cd/A97630_01/appdev.920/a96590/adg13trg.htm
Its always better to use a foreign key constraint for ensuring that the value that appears in table b is present in table a, in this case there should be a foreign key in your table StarsIn for column starName referencing name in MovieStar table

Getting INSERT errors when I do UPDATE?

At work we have a SQL Server database. I don't know the db that well. I have created a new column in the table for some new functionality....straight away I have started seeing errors
My statement was this:
ALTER TABLE users
ADD locked varchar(50) NULL
GO
The error is:
Insert Error: Column name or number of supplied values does not match table definition
I have read that the error message appears when during an INSERT operation either the number of supplied column names or the number of supplied values does not match the table definition.
But I have checked so many times and i have changed the PHP code to include this columns data yet I still receive the error.
I have run the SQL query directly on the db and still get the error.
Funny enough the query which gets the error is an Update.
UPDATE "users"
SET "users"."date_last_login" = GETDATE()
WHERE id = 1
Have you considered it could be a trigger causing it? 
This is the error message you would get.
If its an Update action causing it check trigger actions that Updates on that table run.
Do it with:
#sp_helptrigger Users, 'UPDATE';
This will show triggers occuring with ‘update’ actions.
If there is a trigger, grab the triggers name and run the below (but replace TriggerNameHere with real trigger):
#sp_helptext TriggerNameHere;
This will give you any SQL that the trigger runs and could be the INSERT the error message is referring to.
Hope this helps
Aside from TRIGGERS,
the reason for that is because you are using implicit type of INSERT statement. Let's say your previous number of columns on the table is 3. You have this syntax of INSERT statement,
INSERT INTO tableName VALUES ('val1','val2','val3')
which executes normally fine. But then you have altered the table to add another column. All of your INSERT queries are inserting only three values on the table which doesn't matches to the total number of columns.
In order to fix the problem, you have to update all INSERT statements to insert 4 values on the table,
INSERT INTO tableName VALUES ('val1','val2','val3', 'val4')
and it will normally work fine.
I'll advise you to use the EXPLICIT type of INSERT wherein you have to specify the columns you want to insert values with. Eg,
INSERT INTO tableName (col1, col2, col3) VALUES ('val1','val2','val3')
in this ways, even if you have altered your tables by adding additional columns, your INSERT statement won't be affected unless the column doesn't have a default value and which is non-nullable.

insert data in multiple tables

hi i have a problem to insert data in multiple tables. i have define primary key & reference key in tables now i want to insert data in both tables in single query.......how can i do this...........???????
Your question isn't exactly clear on what the particular problem is. I can see three possibilities:
1. You want to insert into two tables wiht a single INSERT statement
2. You want to do two inserts, but without anything else being able to 'get in the middle'
3. You want to insert into one table, then get the primary key to insert into the second table
The answer to 1. is simple:
You can't.
The answer to 2. is simple too:
BEGIN TRANSACTION
INSERT INTO <table1> (a,b,c) VALUES (1,2,3)
INSERT INTO <table2> (a,b,c) VALUES (1,2,3)
COMMIT TRANSACTION
The answer to 3. is has several possibilities. Each depending on exactly what you want to do. Most likely you want to use SCOPE_IDENTITY() but you may also want to look up ##identity and IDENT_CURRENT() to understand the various different options and complexities.
BEGIN TRANSACTION
INSERT INTO <dimension_table> (name)
VALUES ('my new item')
INSERT INTO <fact_table> (item_id, iteam_value)
VALUES (SCOPE_IDENTITY(), 1)
COMMIT TRANSACTION
This is what transactions are meant for. Standard SQL does not permit a single statement inserting into multiple tables at once. The correct way to do it is:
-- begin transaction
insert into table 1 ...
insert into table 2 ...
commit
Does your language support the INSERT ALL construct? If so, that is the best way to do this. In fact it's the only way. I posted an example of this construct in another SO thread (that example syntax comes from Oracle SQL).
The other option is to build a transactional stored procedure which inserts a record into the primary key table followed by a record into the referencing table.
And 1 of your choice to do that is use ORM (like Hibernate, NHibernate) the you make your object and set other relation to it and finally just save the main object , like:
A a;
B b;
C c;
a.set(b);
a.set(c);
DAO.saveOrUpdate(a);
you must notice your DAO.saveOrUpdate(a); line of code just work with hibernate but it insert data into 3 table A, B, C.