update multiple tables with trigger - sql

I want to update two tables when a user wants to update a view.
create trigger update_mID
instead of update of mID on LateRating
for each row
begin
update Movie, Rating
set mID = new.mID
where mID = Old.mID;
end;
I want to update bot the Movie relation and the Rating relation, however, I have not yet experienced a trigger that is able to update multiple tables. Can someone please indicate how I can overcome this?
UPDATE: This is for a exercise to test my trigger scripting skills. The requirement is that I have to write it in one trigger query. #CL. I tried putting two update statements between the begin and end keywords, however, it says that there is a syntax error.... is there a specific way to put two updates between the begin and end?

A single UPDATE statement can modify only a single table.
Use two UPDATEs:
UPDATE Movie SET mID = NEW.mID WHERE mID = OLD.mID;
UPDATE Rating SET mID = NEW.mID WHERE mID = OLD.mID;

You could do a REPLACE INTO statement like the following:
DROP TRIGGER IF EXISTS `update_mID`;CREATE DEFINER=`USER`#`localhost` TRIGGER
`update_mID` AFTER UPDATE ON `tblname` FOR EACH ROW REPLACE INTO
USER_DATABASENAME.TBLNAME (COLUMNNAME1,COLUMNNAME1) SELECT COLUMNNAME1,COLUMNNAME1
FROM USER_DBNAME.TBLNAME
This can even be two separate databases like the example below:
DROP TRIGGER IF EXISTS `update_mID`;CREATE DEFINER=`USER`#`localhost` TRIGGER
`update_mID` AFTER UPDATE ON `tblname from DB1` FOR EACH ROW REPLACE INTO
USER_DATABASENAME1.TBLNAMEDB2 (COLUMNNAME1,COLUMNNAME1) SELECT
COLUMNNAME1,COLUMNNAME1 FROM USER_DBNAME2.TBLNAME

Related

Can I manually trigger before insert function for already inserted records in Postgres?

I am using PostgreSQL 14.5
I have a beneficiaries table where people are registered and I have BEFORE INSERT trigger function that generates a unique ID based on their location (if Paris - PAR-001, if London - LON-004, etc) and it works.
But the problem is, lots of records are inserted before writing this function, and since the function is triggered BEFORE INSERT I can't have the IDs for them.
I have seen the documentation and didn't find how to trigger the function for previous records
Can I manually trigger this function for all records once or any other solution?
Add an additional trigger like this:
CREATE TRIGGER temp BEFORE UPDATE ON tab
FOR EACH ROW WHEN (OLD.id IS NULL)
EXECUTE FUNCTION your_trigger_func();
The trigger function is the one you use in your BEFORE INSERT trigger. Then update all these rows:
UPDATE tab SET id = id WHERE id IS NULL;
You can drop the trigger when you are done.
You can perform the update in batches and run VACUUM on the table in between, to avoid bloat by a single massive update.

SQL Server : make update trigger don't activate with no changing value

I want to track the update changes in a table via a trigger:
CREATE TABLE dbo.TrackTable(...columns same as target table)
GO
CREATE TRIGGER dboTrackTable
ON dbo.TargetTable
AFTER UPDATE
AS
INSERT INTO dbo.TrackTable (...columns)
SELECT (...columns)
FROM Inserted
However in real production some of the update queries select rows with vague conditions and update them all regardless of whether they are actually changed, like
UPDATE Targettable
SET customer_type = 'VIP'
WHERE 1 = 1
--or is_obsolete = 0 or register_date < '20160101' something
But due to table size and to analyze, I only want to choose those actually modified data for tracking. How to achieve this goal?
My track table has many columns (so I do not prefer checking inserted and deleted column one by one) but it seldom changes structure.
I guess the following code will be useful.
CREATE TABLE dbo.TrackTable(...columns same as target table)
GO
CREATE TRIGGER dboTrackTable
ON dbo.TargetTable
AFTER UPDATE
AS
INSERT INTO dbo.TrackTable (...columns)
SELECT *
FROM Inserted
EXCEPT
SELECT *
FROM Deleted
I realize this post is a couple months old now, but for anyone looking for a well-rounded answer:
To exit the trigger if no rows were affected on SQL Server 2016 and up, Microsoft recommends using the built-in ROWCOUNT_BIG() function in the Optimizing DML Triggers section of the Create Trigger documentation.
Usage:
IF ROWCOUNT_BIG() = 0
RETURN;
To ensure you are excluding rows that were not changed, you'll need to do a compare of the inserted and deleted tables inside the trigger. Taking your example code:
INSERT INTO dbo.TrackTable (...columns)
SELECT (...columns)
FROM Inserted i
INNER JOIN deleted d
ON d.[SomePrimaryKeyCol]=i.[SomePrimaryKeyCol] AND
i.customer_type<>d.customer_type
Microsoft documentation and w3schools are great resources for learning how to leverage various types of queries and trigger best practices.
Prevent trigger from doing anything if no rows changed.
Writing-triggers-the-right-way
CREATE TRIGGER the_trigger on dbo.Data
after update
as
begin
if ##ROWCOUNT = 0
return
set nocount on
/* Some Code Here */
end
Get a list of rows that changed:
CREATE TRIGGER the_trigger on dbo.data
AFTER UPDATE
AS
SELECT * from inserted
Previous stack overflow on triggers
#anna - as per #Oded's answer, when an update is performed, the rows are in the deleted table with the old information, and the inserted table with the new information –

Insert trigger will not work properly

I am trying to create a database trigger that will update certain characters in a field for a table when a user inserts data into the table...
Ex.
ID EXCHANGE LEADRT
1 new L-3
2 new 3
3 new 5
So I would want to leave id 1 alone because the format for the LEADRT is correct but ids 2 and 3 are not.
CREATE TRIGGER triggerupdate ON PoleUnits FOR INSERT,
UPDATE AS
if not exists (select * from Poleunits where LEADRT like '%L-%')
update PoleUnits set LEADRT = STUFF (LEADRT, 1, 0,'L-');
Any ideas why I can't get this to work or better suggestions on how to accomplish this?
In insert and update triggers you have access to a specific table called inserted where the rows to be inserted/updated are held. Those are not real tables, they are just logical tables with the same structure as the table on which the trigger fired.
Your current logic works on the original table, thus working with all the existing data, but not with the data you are actually inserting, i.e. it will update everything except the data you actually want updated. Something like this could work:
CREATE TRIGGER triggerupdate ON PoleUnits
FOR INSERT, UPDATE AS
update PoleUnits
set LEADRT = STUFF (PoleUnits.LEADRT, 1, 0,'L-')
from PoleUnits
inner join inserted -- this is basically a self join
on PoleUnits.ID = inserted.ID
where PoleUnits.LEADRT not like '%L-%'
This will only update those rows in PoleUnits that are being inserted, and only if their LEADRT field is not in the L- format.

How to check if a column is being updated in an INSTEAD OF UPDATE Trigger

I am making some tweaks to a legacy application built on SQL Server 2000, needless to say I only want to do the absolute minimum in the fear that it may just all fall apart.
I have a large table of users, tbUsers, with a BIT flag for IsDeleted. I want to archive off all current and future IsDeleted = 1 user records into my archive table tbDeletedUsers.
Moving the currently deleted users is straight forward, however I want a way to move any future users where the IsDeleted flag is set. I could use a standard AFTER trigger on the column however I plan to add some constraints to the tbUser table that would violate this, what I'd like is for my INSTEAD OF UPDATE trigger to fire and move the record to archive table instead?
I guess my question is... is it possible to trigger an INSTEAD OF UPDATE trigger on the update of an individual column? This is what I have so far:
CREATE TRIGGER trg_ArchiveUsers
INSTEAD OF UPDATE ON tbUsers
AS
BEGIN
...
END
GO
If so an example (SQL 2000 compatible) would be much appreciated!
Using the UPDATE(columnname) test, you can check in a trigger whether a specific column was updated (and then take specific actions), but you can't have a trigger fire only on the update of a specific column. It will fire as soon as the update is performed, regardless of the fact which column was the target of the update.
So, if you think you have to use an INSTEAD OF UPDATE trigger, you'll need to implement two kinds of actions in it:
1) insert into tbDeletedUsers + delete from tbUsers – when IsDeleted is updated (or, more exactly, updated and set to 1);
2) update tbUsers normally – when IsDeleted is not updated (or updated but not set to 1).
Because more than one row can be updated with a single UPDATE instruction, you might also need to take into account that some rows might have IsDeleted set to 1 and others not.
I'm not a big fan of INSTEAD OF triggers, but if I really had to use one for a task like yours, I might omit the UPDATE() test and implement the trigger like this:
CREATE TRIGGER trg_ArchiveUsers
ON tbUsers
INSTEAD OF UPDATE
AS
BEGIN
UPDATE tbUsers
SET
column = INSERTED.column,
…
FROM INSERTED
WHERE INSERTED.key = tbUsers.key
AND INSERTED.IsDeleted = 0
;
DELETE FROM tbUsers
FROM INSERTED
WHERE INSERTED.key = tbUsers.key
AND INSERTED.IsDeleted = 1
;
INSERT INTO tbDeletedUsers (columns)
SELECT columns
FROM INSERTED
WHERE IsDeleted = 1
;
END

Create a trigger in sql server 2008

I am trying to create a trigger for a cinema database.
I need it to update once a rating is added for a movie showing the text "rating added". The table name is
movie_ratings
the primary key is = movie_rating
I am not really sure how to do it, I have looked online but still are not too sure. I was wondering if anyone could help.
Thanks
Here is the syntax to create a trigger which will fire when a row is inserted.
create trigger movie_rating_added on movie_ratings for insert
as
-- trigger code goes here
go
Inside the trigger, you have access to a virtual table called inserted, which has the same schema as movie_ratings, but which contains only the rows which were inserted.
I'm not clear on exactly what you want the trigger to do, but for example you could do something like this:
create trigger movie_rating_added on movie_ratings for insert
as
update m set last_action = "rating added"
from movies m
join inserted i on i.movie_id=m.id
go
Which is supposing the existence of some fields and tables that you might not have, but hopefully it gives you a useful example.