如何创建一个SQL触发器,它不会让您删除在Northwind数据库上发出超过10个订单的员工?
我已经走到了这一步:
CREATE TRIGGER emplDel ON Employees AFTER DELETE
AS
BEGIN
DECLARE @num INT
SELECT @num= COUNT(OrderID)
FROM Orders
WHERE EmployeeID= --what id should i use?
if (@num>10)
ROLLBACK
END
答案 0 :(得分:1)
也许是这样的:
CREATE TRIGGER empDel ON [Employees]
INSTEAD OF DELETE
AS
BEGIN
WITH orderCounts
AS (
SELECT [EmployeeID],
(
SELECT COUNT(*)
FROM [Orders] AS [o]
WHERE [o].[EmployeeID] = [d].[EmployeeID]
) AS OrderCount
FROM [Deleted] AS [d]
)
DELETE FROM [Employees]
WHERE EXISTS ( SELECT *
FROM [orderCounts] oc
WHERE oc.[EmployeeID] = [Employees].[EmployeeID] AND
[oc].[OrderCount] < 10 );
END;