SQL triggers
-- Create the trigger
CREATE TRIGGER TrackRetiredProducts
ON Products
AFTER DELETE
AS
INSERT INTO RetiredProducts (Product, Measure)
SELECT Product, Measure
FROM deleted;
Insted of Trigger
The company doesn't want regular users to add discounts. Only the Sales Manager should be able to do that.
To prevent such changes, you need to create a new trigger called PreventNewDiscounts
.
The trigger should be attached to the Discounts
table and prevent new rows from being added to the table.
-- Create a new trigger
Create Trigger PreventNewDiscounts
ON Discounts
INSTEAD OF INSERT
AS
RAISERROR ('You are not allowed to add discounts for existing customers.
Contact the Sales Manager for more details.', 16, 1);
Advance Triggers with if and else
-- Create a new trigger to confirm stock before ordering
CREATE TRIGGER ConfirmStock
ON Orders
INSTEAD OF INSERT
AS
IF EXISTS (SELECT *
FROM Products AS p
INNER JOIN inserted AS i ON i.Product = p.Product
WHERE p.Quantity < i.Quantity)
BEGIN
RAISERROR ('You cannot place orders when there is no stock for the order''s product.', 16, 1);
END
ELSE
BEGIN
INSERT INTO Orders (OrderID, Customer, Product, Price, Currency, Quantity, WithDiscount, Discount, OrderDate, TotalAmount, Dispatched)
SELECT OrderID, Customer, Product, Price, Currency, Quantity, WithDiscount, Discount, OrderDate, TotalAmount, Dispatched FROM inserted;
END;
Comments
Post a Comment