MySQL Triggers (Before Insert) - mysql

I have two tables inspect, with columns inspect_id (pk), inspect_loc and duplicate_inspect with columns inspect_id, inspect_loc. I need a MySQL trigger that inserts Data into duplicate_inspect only if the data being inserted into inspect is already available.

For example ..
CREATE TRIGGER duplicate
BEFORE INSERT ON duplicate_inspect
FOR EACH ROW
BEGIN
IF new.inspect_id = inspect_id THEN
INSERT INTO duplicate_inspect (inspect_id,inspect_loc) values('','');
END IF;
END
I can't test now, but you need the values. (i think all code it's ok).

Related

MySQL merge data on duplicate key

I'm adopting dashboard now and I created two tables for selecting from frontend;
DATA_SELECTED_HISTORY
DATA_SELECTED_NOW
My frontend page get data from DATA_SELECTED_NOW and my backend algorithm put new data to this database.
I want to put my new data to DATA_SELECTED_NOW,
and the former data to be pushed to DATA_SELECTED_HISTORY when being faced with duplicate key.
I think I could use a swap table solution or insert(select subquery) + insert on duplicate key solution, but I don't get an idea anymore.
How can I use this solution in SQL?
you can use trigger in this case, to check duplication before insert to DATA_SELECTED_NOW and insert in DATA_SELECTED_HISTORY if it duplicates, check the below code
CREATE TRIGGER TRIGGER_Name
BEFORE INSERT ON DATA_SELECTED_NOW
FOR EACH ROW
BEGIN
IF (EXISTS(SELECT 1 FROM User WHERE key = NEW.Key)) THEN
-- you can replace "key = NEW.Key " with your logic to check
-- inset into DATA_SELECTED_HISTORY
END IF;
END$$

What is proper way to set and compare variable inside an sql trigger

Am populating a table using a trigger after an insert event occurs on another table and that worked fine. However i then noticed that the trigger would still insert a new row for existing records. To fix this, I want to create the trigger again but this time it would only fire if a condition is met...but not having previously used triggers in the past am getting a syntax error and not able to identify what am doing wrong. Kindly have a look and help me fix this
CREATE TRIGGER `students_gen_insert`
AFTER INSERT ON `students` FOR EACH ROW
BEGIN
INSERT INTO records (student_id, subject_id)
SELECT new.student_id, subjects.subject_id
FROM subjects
WHERE category = new.class;
END;
Am currently using MySql 5.6.17 version.
It is generally not a good idea to SELECT from the table the trigger is on, and forbidden to UPDATE or INSERT (not that you are doing those). Assuming you are trying to get the values for the row just inserted, the first SET ... SELECT you have is needless; just use NEW.fieldname to get the fields of the inserted row.
The second SET ... SELECT and following condition are a bit confusing. If referential integrity is being maintained, I would think it would be impossible for the records table to refer to that particular student_id of the students table at the point the trigger is executed. Perhaps this was to avoid the duplicate inserts from the trigger's previous code? If so, it might help for you to post that so we can pinpoint the actual source of redundant inserts.

whenever i update my table i want to store my old data(old-row) in a new table

CREATE TRIGGER items_
ON test
after update
AS
begin
INSERT INTO test2(id,namecan)
SELECT id,namecan from test
end
I Have tried with trigger but i didnt get any results so please help me how to deal with it
methods involving two stored procedures are also welcome
You could do it with a stored procedure, but I would use a trigger.
With a stored procedure, I'd perceive you using a cursor on the otherDatabase table to read through the records and compare each with the values in Table1 to determine whether Table1's data needed to be written to Table2, and if so, to do it.
With a trigger, I would simply update the data in Table1 by whatever means, without concerning myself with what the overwriting data is, and in the trigger,
use the old and new values using the ##Inserted & ##Deleted (system) tables to determine if the old values (##Deleted) needed to be written to Table2.
If you don want to use triggers, you can go for this concept..
Let there is a form from which you are inserting the values on a table say register table. And the action of the form in going to servlet MyServlet. In Myservlet
you can first fetch the data from the Register table and store it into the Rsultset object let rs. And after that insert the rs into a new table.
Please let me know if m not clear to u..
Your trigger syntax is wrong
delimiter //
CREATE TRIGGER items_ after update
ON test
for each row
begin
INSERT INTO test2(id,namecan) values (old.id,old.namecan);
end; //
delimiter ;
So this trigger will make an entry to the test2 table every time you update row in the test table with the old row values from test table.
You should call old.id and old.namecan (i assume that table 'test' have 'id' and 'namecan' field)to get the older data. your trigger body should look like this
begin
INSERT INTO test2(id,namecan) value(old.id, old.namecan)
end
'old' will reference to record which you update.

SQL Server - After Insert/ For Insert - Rollback

I have the below trigger:
CREATE Trigger instructor_expertise on CourseSections
After Insert
As Begin
......
If (Not Exists(Select AreaName From AreasOfInstructor Where (InstructorNo = #InstructorNo AND AreaName = #AreaName)))
Begin
RAISERROR('Course not in instructors expertise', 16, 1)
rollback transaction
End
GO
My question is, does 'rollback transaction' remove the row?
What if it's 'For Insert' instead, does 'rollback transaction' remove the row in that case?
Thanks!!!
Your INSERT statement always runs in a transaction - either you've explicitly defined one, or if not, then SQL Server will use an implicit transaction.
You're inserting one (or multiple) row into your table. Then - still inside the transaction - the AFTER INSERT trigger runs and checks certain conditions - typically using the Inserted pseudo table available inside the trigger, which contains the rows that have been inserted.
If you call ROLLBACK TRANSACTION in your trigger, then yes - your transaction, with everything it's been doing, is rolled back and it's as if that INSERT never happened - nothing shows up in your database table.
Also: FOR INSERT is the same as AFTER INSERT in SQL Server - the trigger is executed after the INSERT statement has done its job.
One thing to keep in mind (which a lot of programmers get wrong): the trigger is fired once per statement - NOT once per row! So if you insert 20 rows at once, the trigger is fired once and the Inserted pseudo table inside the trigger contains 20 rows. You need to take that into account when writing the trigger - you're not always dealing with just a single row being inserted!
no it is not possible because when their is no row exist then it will go in begin block ...

MySQL Trigger: compare record with previous record before insert

When I insert data in db I have to compare the current record with the previous one. If neccassary, some values of the current record needs to be modified.
I've tried some pieces of SQL like below, but all give SQL errors. This one gives me an error says that I select more than 1 records.
DELIMITER $$
CREATE
TRIGGER set_moment_display
BEFORE INSERT ON data
FOR EACH ROW
BEGIN
DECLARE moment DATETIME;
SELECT press_moment_1 INTO moment FROM data LIMIT 1;
IF moment > NEW.press_moment_1 THEN SET NEW.press_moment_1 = moment;
END IF;
END$$
DELIMITER ;
How do I achieve what I've described above.
The problem here is that, since a SQL database has no implicit concept of row ordering (you supply the ordering criteria on every query), there is no "previous" row for the trigger to look at. The "previously inserted row" has no meaning in the context of an insert trigger.
Suppose for a moment that it did and there were several processes inserting rows in the table. When the trigger fired for process #1's insert, which row is the "previous" row? The one previously inserted by process #1? Suppose the chronologically "most recent" row was actually inserted by process #3?
If you need to do this it cannot be done in a trigger unless you can use a know key value to identify the row you understand as "most recent". Otherwise it must be handled in the application that is doing the inserts.
You can use the alias "OLD."
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
UPDATE
Jim Garrison properly pointed up to me the mistake, "BEFORE INSERT" doesn't have "OLD." values, this alias works only for UPDATE and DELETE.