tags:

views:

19

answers:

1

Hello,

I have SQL Server 2008 database with two tables. The first table is called Shelf. The second table is called Product. Each Product will belong to a Shelf. Based on this, I have a table structure that looks like:

**Product**
ID (int)
ShelfID (int)
Description (text)

**Shelf**
ID (int)
AisleNumber (int)
TotalProducts (int)

When a Product is inserted or removed, I need to update the "TotalProducts" value in the associated shelf. In an attempt to try this, I'm using a Trigger. However, I do not fully understand how triggers work. Can someone please show me how to accomplish this?

Thank you

+2  A: 

When you insert or update a product, you need to work out what ShelfIDs are affects. This is the INSERTED reference below. Then you need to work out the number of products for these ShelfIDs (the JOIN/COUNT bit) and update the Shelf table.

You'll also need something for DELETE too: just reference the special DELETED table

This will run as part of the INSERT/DELETE statement

CREATE TRIGGER TRG_Product_I On product FOR INSERT
AS
SET NOCOUNT ON

UPDATE
   S
SET
   TotalProducts = foo.NewTotalProducts
FROM
   Shelf S
   JOIN
   (SELECT
        ShelfID, COUNT(*) AS NewTotalProducts
    FROM
       INSERTED I
       JOIN
       product P ON I.ShelfID = P.ShelfID
    GROUP BY
       ShelfID
   ) foo ON S.ShelfID = foo.ShelfID
gbn