Building and Optimizing Triggers in SQL Server
Florin Angelescu
Instructor
INSERT, UPDATE, and DELETE statements for tables or viewsOutput from table Products used for this example:
| Product | Price | Currency | Quantity | Measure |
|---------|-------|----------|----------|---------|
| Apple | 2.00 | USD | 25000 | kg |
| Apricot | 1.55 | USD | 2500 | kg |
| Avocado | 3.00 | USD | 1000 | kg |
| Banana | 1.80 | USD | 35000 | kg |
ProductsDELETETrackRetiredProductsWhen rows are removed from the Products table...
Save the required information from those rows to the table RetiredProducts.
| Product | Price | Currency | Quantity | Measure |
|---------|-------|----------|----------|---------|
| Apple | 2.00 | USD | 25000 | kg |
| Apricot | 1.55 | USD | 2500 | kg | X
| Avocado | 3.00 | USD | 1000 | kg |
| Banana | 1.80 | USD | 35000 | kg |
| Product | Measure | RemovalDate |
|---------|---------|-------------|
| Apricot | kg | 19.04.2019 |
CREATE TRIGGER TrackRetiredProductsON ProductsAFTER DELETEAS INSERT INTO RetiredProducts (Product, Measure) SELECT Product, Measure FROM deleted;
| Special table | INSERT | UPDATE | DELETE |
|---|---|---|---|
| inserted | new rows | new rows | N/A |
| deleted | N/A | updated rows | removed rows |
CREATE TRIGGER TrackRetiredProducts
ON Products
AFTER DELETE
AS
INSERT INTO RetiredProducts (Product, Measure)
SELECT Product, Measure
FROM deleted;
Building and Optimizing Triggers in SQL Server