I have two tables:
CREATE TABLE EventsCnfig
(
Id int,
InspectionId int,
Event int
);
And this:
CREATE TABLE Inspections
(
Id int,
IsRepaired Bit
);
InspectionId in EventsCnfig table is foreign key of Inspections table with relation of one to many.
Here is SQL plunker
I need to create trigger when any row in EventsCnfig table updated the value of the column Event to -1 or inserted new row with the Event value -1 the row in Inspections table with appropriate Id has to update IsRepaired value in column to 1(true).
How can I write the trigger to implement the desired logic?
I would write two triggers - one for UPDATE, another for INSERT - if you try to do this in a single trigger, the code gets messy because of the checks for "is this an INSERT or UPDATE operation?" etc. - don't do that....
AFTER UPDATE trigger:
CREATE TRIGGER dbo.TrgEventsConfigUpdate
ON dbo.EventsConfig
AFTER UPDATE
AS
UPDATE insp
SET IsRepaired = 1
FROM dbo.Inspections insp
INNER JOIN Inserted i ON i.InspectionId = insp.Id
INNER JOIN Deleted d ON d.Id = i.Id
WHERE i.[Event] = -1 AND d.[Event] <> -1
Basically, after an update, you need to look at the Inserted and Deleted pseudo tables which contain the updated rows - if the new row (after the update) has a value of -1, while the old row (before the update) did not --> then the column Event has been updated to -1 and thus the IsRepaired in the table Inspections needs to be set to 1 (true).
AFTER INSERT trigger:
CREATE TRIGGER dbo.TrgEventsConfigInsert
ON dbo.EventsConfig
AFTER INSERT
AS
UPDATE insp
SET IsRepaired = 1
FROM dbo.Inspections insp
INNER JOIN Inserted i ON i.InspectionId = insp.Id
WHERE i.[Event] = -1
Same idea - just a bit simpler, since there's no "old" row to compare to: if the column in the list of inserted rows has a value of -1, then update the Inspections table for those InspectionId values to be 1.
Here you can read all about triggers:
How to use update trigger to update another table?
https://msdn.microsoft.com/en-us/library/ms189799.aspx
http://www.sqlteam.com/article/an-introduction-to-triggers-part-i
There should be more than enough information to build the trigger by yourself.
If you have a "finished" trigger that does not work the way you want, you can post it here and the community will help you out.
Related
Hi I use SQL SERVER 2012 and I have two table named tbcustomer and tbcustomerdetail. Both tables have column customerID.
I manage only tbcustomerdetail. If I update tbcustomerdetail where customerID='001' then I need the trigger to update tbcustomer where customerID='001'
I try this but not found spelling.
CREATE TRIGGER Deletecustomer
ON tbcustomerdetail
FOR UPDATE
AS
BEGIN
update tbcustomer tbcustomer.status=0 where tbcustomer.customerID=updated.customerID;
END
//updated.customerID is the ID on column tbcustomerdetail where customerID is '001'.
I also tried AFTER UPDATE but it doesn't work.
Updated does not exist, in a trigger you have two views Deleted which contains previous data and Inserted contains the new one
As I mentioned they are views, and contains data for all the rows affected by the statement, so, you need to use them in a join
CREATE TRIGGER Deletecustomer
ON tbcustomerdetail
FOR UPDATE
AS
BEGIN
UPDATE C
SET Status = 0
FROM tbCustomer C
JOIN Inserted I ON C.CustomerID = I.CustomerID
END
I'm currently developing a project where I need to create a record in one table and leave the last column as NULL and update this later with the PK of another table (to establish a link).
Table 1 is a table for courses and table 2 is a table for the feedback form for each course.
The user first makes the course which is inserted in to table 1, THEN they make the feedback form which is inserted in to table 2.
Now I wanted to use a PK+FK relation here but, I can't set the FK of table 1 as the record hasn't yet been created in table 2.
For example, table 1 has the columns:
id(int)(PK), column1(int), column2(int), linkColumn(int)
Table 2 has the columns:
id(int)(PK), column1(int),...
I need to be able to make a record in table 1 and set linkColumn to NULL initially.
Then I need to create a record in table 2 and update linkColumn in table 1 with the Primary key of the newly created record in table 2.
How would I go about this?
Thanks!
Edit: I'm using PHP as the SQL handler
Use Triggers on insert for each row on Table2.
What Database are you using?
EDIT:
CREATE TRIGGER T_TABLE2_AI
AFTER INSERT
ON TABLE2 FOR EACH ROW
BEGIN
update Table1 set linkColumn = :new.ID where column1 = :new.column1;
END;
I have 3 tables Data table, LookUp_1,LookUp_2 all with column id which are primary key columns. The score1_id and score2_id columns are foreign key columns. score1_id links with id in LookUp_1 and score2_id links with id in LookUp_2.
My question is:
I need to create an after insert trigger which will update the calculation column from null to a specific number/value. This only happens when a new record is inserted into the Data table and it only should affect the newly created record. So for the example i have, id 1 is a newly inserted record, and now the trigger should go on and update the calculation column using the score1_id and score2_id. So it should go into LookUp1 and LookUp2 and check the weights for each id. So for example: 3=7 and 2=3. So after the trigger is completed the record should be updated with calculation column = 21 (since we are multiplying the weights)
so the updated table record should look like this:
Any suggestions on how to go about this?? Or some examples anyone has in mind?
I would greatly appreciate it!
Here is your trigger (well you need to finish it)
Need to update now that you posted column names.
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
declare #v1 int = (Select weight from lookup1 where id=inserted.scoreid1
,#v2 int = (Select weight from lookup2 where id=inserted.scoreid2)
update data
set calculation = #v1*#v2
where inserted.id = data.id
END
or for multiple inserts:
CREATE TRIGGER [triggername]
ON [data]
AFTER
INSERT
AS
BEGIN
update data
set calculation = l1.weight*l2.weight
from data d
join lookup_1 l1 on d.scoreID1=l1.id
join lookup_2 l2 on d.scoreid2=l2.id
join inserted on inserted.id = d.id
END
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.
I have the following trigger but need ti find the identity of the row so I don't update all records in the table. How can I get the identity of the affected row?
BEGIN
UPDATE tb_Division SET LastModified = GetDate() WHERE "id of inserted/updated row"
END
Since a trigger in MS SQL Server does not distinguish between single-record and multi-record operations, you should JOIN the table with the INSERTED pseudo table or use a subselect:
UPDATE tb_Division
SET LastModified = GETDATE()
WHERE id IN (SELECT id FROM INSERTED)
id being the primary key column of your table.
Have you looked at the id of the inserted logical table? You have to be careful when using triggers, as a trigger may be operating on more than one row:
UPDATE tb_Division AS td
SET LastModified = GetDate()
FROM INSERTED AS i
WHERE td.id = = i.id
See here for more details, and from MSDN:
DML triggers use the deleted and inserted logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is tried. The deleted and inserted tables hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use:
Mind you - a trigger can deal with a ton of rows at once - you'll have to take that into account!
You need to join your table to be updated with the Inserted pseudo-column on that ID field:
UPDATE dbo.tb_Division
SET LastModified = GetDate()
FROM Inserted i
WHERE tb_Division.Id = i.Id
or something like that.