SQL Server 2012 Trigger – How to Update Another Table When Inserting and Deleting

sql-server-2012

I need help with modifiying this trigger. I'm new to triggers. When it's executed it is supposed either to delete 1 from nrOfCopies or add 1 to nrOfCopies on a based on the specific isbn(a char(20)), but this does it on all the rows. Becuase its a trigger i cannot use a parameter.

ALTER TRIGGER trgUpdatesNrOfCopies
ON bookcopy
AFTER INSERT, DELETE
AS
BEGIN
   SET NOCOUNT ON

   IF NOT EXISTS(SELECT*FROM INSERTED)
   BEGIN    
       PRINT 'DELETE'
       UPDATE book
       SET nrOfCopies=(SELECT nrOfCopies FROM bookcopy WHERE isbn )
   END
   ELSE IF NOT EXISTS(SELECT * FROM DELETED)
   BEGIN
       PRINT 'INSERT'
       UPDATE book
       SET nrOfCopies=nrOfCopies+1
   END
END

The column I need to specify is called isbn. How can I specify it to only make the changes on one specific isbn column?

When this trigger is being fired i get 'Primary key violation' error message. I dont know how to fix this!

Best Answer

Something along the lines of the below... just join to the inserted/deleted tables. Please do test this though with real life scenarios:

ALTER TRIGGER trgUpdatesNrOfCopies
ON bookcopy
AFTER INSERT, DELETE
AS
BEGIN
   SET NOCOUNT ON

   IF NOT EXISTS(SELECT*FROM INSERTED)
   BEGIN    
       PRINT 'DELETE'
       UPDATE b
       SET nrOfCopies= nrOfCopies-1
       from book b
       inner join DELETED d
         on d.isbn = b.isbn
   END
   ELSE IF NOT EXISTS(SELECT * FROM DELETED)
   BEGIN
       PRINT 'INSERT'
       UPDATE b
       SET nrOfCopies=nrOfCopies+1
       from book b
       inner join inserted i
         on i.isbn = b.isbn
   END
END