-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathtriggers-3.sql
50 lines (44 loc) · 1.52 KB
/
triggers-3.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
-- Alter the ProductType Table
ALTER TABLE ProductType
ADD AmountOfProducts INT
GO
-- Update the existing records
UPDATE ProductType
SET AmountOfProducts = (SELECT COUNT(*)
FROM Product
WHERE Product.ProductTypeID = ProductType.ProductTypeID)
-- Table prefixes are mandatory here, why?
GO
-- Trigger
-- Delete the trigger if it exists already
DROP TRIGGER TR_Product_SynchronizeProductType
GO
CREATE TRIGGER TR_Product_SynchronizeProductType
ON Product
FOR INSERT, UPDATE, DELETE
AS
SET NOCOUNT ON
DECLARE @oldProductTypeID INT
DECLARE @newProductTypeID INT
IF UPDATE(ProductTypeId)
BEGIN
SELECT @newProductTypeID = ProductTypeID from inserted
UPDATE ProductType
SET AmountOfProducts = AmountOfProducts + 1
WHERE ProductTypeID = @newProductTypeID
END
SELECT @oldProductTypeID = ProductTypeID from deleted
if @oldProductTypeID is not null
BEGIN
UPDATE ProductType
SET AmountOfProducts = AmountOfProducts - 1
WHERE ProductTypeID = @oldProductTypeID
END
GO
/* Remark:
- deleted virtual table contains copies of updated or inserted rows
During update or delete rows are moved from the triggering table to the deleted table
- inserted virtual table contains copies of updated or inserted rows.
During update or insert each affected row is copied from the triggering table to the inserted table
All rows from the inserted table are also in the triggering table
*/