Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server trigger to update another table's column

Tags:

sql

sql-server

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?

like image 946
Crysis Hhtht Avatar asked Feb 03 '19 15:02

Crysis Hhtht


People also ask

How UPDATE a column with trigger in SQL?

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.

Can we use UPDATE in trigger?

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.

How do I create a trigger for insert and UPDATE in SQL Server?

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.


2 Answers

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

like image 167
El.Hum Avatar answered Oct 19 '22 15:10

El.Hum


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)
like image 24
Arnaud Peralta Avatar answered Oct 19 '22 14:10

Arnaud Peralta