Tvorba a optimalizace triggerů v SQL Serveru
Florin Angelescu
Instructor
CREATE TRIGGER PreventProductChanges
ON Products
INSTEAD OF UPDATE
AS
RAISERROR ('Updates of products are not permitted.
Contact the database administrator if a change is needed.', 16, 1);
CREATE TRIGGER PreventCustomersRemoval
ON Customers
INSTEAD OF DELETE
AS
DECLARE @EmailBodyText NVARCHAR(50) =
(SELECT 'User "' + ORIGINAL_LOGIN() +
'" tried to remove a customer from the database.');
RAISERROR ('Customer entries are not subject to removal.', 16, 1);
EXECUTE SendNotification @RecipientEmail = '[email protected]'
,@EmailSubject = 'Suspicious database behavior'
,@EmailBody = @EmailBodyText;
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)
RAISERROR ('You cannot place orders when there is no product stock.', 16, 1);
ELSE
INSERT INTO dbo.Orders (Customer, Product, Quantity, OrderDate, TotalAmount)
SELECT Customer, Product, Quantity, OrderDate, TotalAmount FROM inserted;

Tvorba a optimalizace triggerů v SQL Serveru