Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create trigger to update a second table but its not working.

What I have tried:

CREATE trigger [dbo].[Report_Update] on [dbo].[SellTable] 
AFTER UPDATE AS
BEGIN
  
    IF UPDATE(TransType) BEGIN
    UPDATE ReportTable
    SET    ReportTable.TransType = inserted.TransType
    FROM   SellTable
     INNER JOIN Inserted ON SellTable.TransID = Inserted.TransID
	
	
    End

	IF UPDATE(Quantity) BEGIN
    UPDATE ReportTable
    SET    ReportTable.TransType = inserted.Quantity
    FROM   SellTable
    INNER JOIN Inserted ON SellTable.TransID = Inserted.TransID
	
    End

	IF UPDATE(Price) BEGIN
    UPDATE ReportTable
    SET    ReportTable.TransType = inserted.Price
    FROM   SellTable
    INNER JOIN Inserted ON SellTable.TransID = Inserted.TransID
    End

	IF UPDATE(Cost) BEGIN
    UPDATE ReportTable
    SET    ReportTable.TransType = inserted.Cost
    FROM   SellTable
 INNER JOIN Inserted ON SellTable.TransID = Inserted.TransID
	End

     
END
Posted
Updated 30-Jan-20 4:17am
Comments
Santosh kumar Pithani 30-Jan-20 7:01am    
Hello,your updating all records for "ReportTable" based on updated "SellTable" columns, i hope there is no addition queries its should be complete in single line

You seem to update the same field of ReportTable for distinct fields of SellTable.
Shouldn't you write
SQL
SET    ReportTable.Quantity = inserted.Quantity
,
SQL
SET    ReportTable.Price = inserted.Price
and
SQL
SET    ReportTable.Cost = inserted.Cost
instead?
 
Share this answer
 
v2
Quote:
SQL
UPDATE ReportTable
SET    ReportTable.TransType = inserted.TransType
FROM   SellTable
INNER JOIN Inserted ON SellTable.TransID = Inserted.TransID
You're updating every record in the ReportTable table with one random value from the updated records.

There is presumably a connection between the records in the two tables? You will need to limit the records you're updating based on that join.
SQL
UPDATE
    ReportTable
SET
    TransType = inserted.TransType
FROM
    ReportTable
    INNER JOIN inserted
    ON inserted.??? = ReportTable.???
;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900