tags:

views:

21

answers:

1

Hello,

I have a SQL Server 2008 database that has a Trigger. This trigger is defined as follows:

CREATE TRIGGER [dbo].[Trigger_Car_Insert] ON [dbo].[Car] FOR INSERT 
AS 
    UPDATE
        [Lot] 
    SET
        [TotalCars]=lotCars.TotalCars
    FROM
        [Lot] l JOIN (
            SELECT 
                c.[LotID], COUNT(*) as 'TotalCars' 
            FROM 
                inserted i JOIN [Car] c ON i.[LotID]=c.[LotID]
                    WHERE
                            c.[IsSold]=0
            GROUP BY
                c.[LotID]
        ) lotCars ON l.[ID]=lotCars.[LotID]

This works well for inserting. However, when a car gets sold, the IsSold flag gets updated to true. When this happens, I want a trigger to update the "TotalCars" property on the Lot table. I know there is an "inserted" and "deleted" table to detect what was just inserted/deleted. However, I cannot figure out the equivalent for updating.

How do I do this on SQL Server 2008? Thank you!

+3  A: 

There is no "updated table" in update trigger. The values before update statement are in "deleted" table and new values are in "inserted" table. You can check whether a specific column was updated or not by using COLUMNS_UPDATED function.

Here is a simple example: An Introduction to Triggers -- Part II

Giorgi