Oracle SQL Trigger insert/update - sql

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

Related

assistance needed with sql statements/expressions

New to sql statements etc and I have an issue with what i am doing using squirrelSQL on linux machine
I Created a table and used the following sql statements:-
INSERT INTO FIRSTTABLE VALUES
(11,'TEN','STEVE'),(21,'TWENTY','JO'),(31,'THIRTY','KIDS')
ALTER TABLE FIRSTTABLE
ADD SURNAME VARCHAR(15);
this works fine however when i attempt to insert data/values into the the surname row i keep experiencing errors, the SQL statement i am using is:-
INSERT INTO FIRSTTABLE (SURNAME)
VALUES ('THOMAS'),('THOMAS'),('THOMAS'),('THOMAS');
This particular statement returns the following error:-
Error: Column 'ID' cannot accept a NULL value.
SQLState: 23502
ErrorCode: 30000
I only wish to add data/values into the surname column,after creating a new column with the alter table statement, i have tried many different combinations including using a SELECT statement prior to the INSERT statement above which also gives errors any guidance will be greatly appreciated,
You are inserting into Surname, without assigning a value to the other fields. You are getting this error message because ID is blank, and should not.
Understand that INSERT creates new rows. If you wish to modify existing rows, use UPDATE
In this case you could use UPDATE FIRSTTABLE SET SURNAME='THOMAS';
Omitting the WHERE clause affects all the fields in the table.
Hope it helps, and good luck in your learning process!
The approach is wrong, you need to:
UPDATE FIRSTTABLE SET SURNAME='THOMAS' WHERE ID IN (11, 21, 31)
Inserting will add a new row to the table. So you need to update a row using
UPDATE FIRSTTABLE SET SURNAME="THOMAS" WHERE ID=11

How to find the error value in sql table

I am inserting values from one table to another table. There are 100000 records in the table. But when I start to insert value from one table to another table there is a problem in any row in my data. I don't know where exactly is that. So how can I know that in which row value is error because the insert statement not complete? After error this stop nothing insert in table.
This is simple statement that I use:
INSERT INTO Person (FirstName, LastName,Email)
SELECT FirstName, LastName, Email
FROM Person.Contact
Without any additional information on the constraints imposed on the target table a very general, slow solution would be
a cursor loop over the selected rows
insert any row within try/catch
on exception output row and error message
For a specific answer to your problem provide more information.
An alternative method is to use SSIS: here you can provide a separate channel for the erroneous rows. This channel can be lead to a separate table collecting all rows causing an error.
quesion is hard to understand, but the usual suspects are:
Attempting to insert Null into a non-nullable column
Foreign Key violations
Constraint violations.
Attempting to insert wrong datatype.
Please edit you question to add error message.
I guess Person is the name of your schema, so maybe you mean
INSERT INTO Person.Person (FirstName, LastName,Email)
SELECT FirstName, LastName, Email
FROM Person.Contact

MySQL trigger with 2 queries

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.

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.

SQL: is it possible to combine an INSERT and SELECT statement into one

I want to add a row using SQLs INSERT statement. Is it possible that as part of this statement I can somehow get the value of the column userId which I don't update but is the AUTO_INCREMENT primary key. I need this value to update another table, however I can't follow the Insert statement immediately with a SELECT statement as there is no other unique identifier in the table on which to select.
INSERT INTO objectUrl(disp_name, loggedIn) VALUES('please change this', true)
Is it possible to get the row number (column name userId) and if so how do you do it?
In MySQL it's called LAST_INSERT_ID(). I believe to be technically correct, the two statements should be wrapped in a transaction so that some other INSERT doesn't mess up what ID you get back.
In SQL Sever you have IDENT_CURRENT(‘tablename’) which will only grab it from that table (still need a transaction to be safe). You could also use SCOPE_IDENTITY() which theoretically will always return the one you expect as long as you aren't doing something weird with your connection.
For MySQL you have:
select last_insert_id()