I have two SQL Server tables called Table A
and Table B
. I have an application which inserts one row into Table A
and three rows into Table B
at the same time. As you can see in the screenshot below, we can link these inserted records based on their ID
column in Table
A and TransID
column in Table B
.
During the data insert on table B, if any rows out of 3 inserted rows contain a value called
Printed
in the Printed
column, I want to update my Table A
's relevant record's PrintStatus
column to Printed
as well.
How do I write a SQL Server trigger for this?
You can do this by using the UPDATE() function inside your trigger. This function accepts the column name as its argument. It returns a boolean.
AFTER UPDATE Trigger in SQL is a stored procedure on a database table that gets invoked or triggered automatically after an UPDATE operation gets successfully executed on the specified table. For uninitiated, the UPDATE statement is used to modify data in existing rows of a data table.
The CREATE TRIGGER statement allows you to create a new trigger that is fired automatically whenever an event such as INSERT , DELETE , or UPDATE occurs against a table. In this syntax: The schema_name is the name of the schema to which the new trigger belongs. The schema name is optional.
Well the best solution is to do this in your code(app) but if there is no way, you can write a Trigger After Insert for Table B like the trigger example below:
CREATE TRIGGER [dbo].[YourTrigger] ON [dbo].[TableB]
AFTER INSERT
AS
DECLARE @id INT
BEGIN
SET NOCOUNT ON;
SET @id = (SELECT DISTINCT ID FROM Inserted)
IF EXISTS (SELECT * FROM Inserted WHERE Printed='Printed')
UPDATE TableA
SET PrintStatus='Printed'
WHERE ID = @id
END
May this help you
It could be correct for your problem : (not sure at 100%)
CREATE TRIGGER TriggerTableB
ON TableB
AFTER INSERT
AS
UPDATE TableA AS A
SET PrintStatus = 'Printed'
WHERE A.TranID = inserted.ID
AND 'Printed' = (SELECT MAX(I.Printed)
FROM inserted AS I)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With