我编写了一个触发器,用于从OrderDetails状态更新为Order状态:
BEGIN
/*
Order Status:
Pending = 0,
Processing = 1,
Proceeded = 2,
Completed = 3,
Cancelled = 4,
Order Detail Status:
Pending = 0,
Processing = 1,
Proceeded = 2,
Emailed = 3,
Ordered = 4,
Cancelled = 5
*/
IF (UPDATE([Status]))
BEGIN
UPDATE [Order]
SET [Status] =
CASE (SELECT MIN(od.[Status]) FROM OrderDetail od WHERE od.OrderId = i.OrderId)
WHEN 5 THEN 4
WHEN 4 THEN 3
WHEN 3 THEN 2
WHEN 2 THEN 2
WHEN 1 THEN 1
WHEN 0 THEN 0
END
FROM INSERTED i
WHERE [Order].Id = i.OrderId
END
END
您可以看到,当OrderDetailStatus = 2或3时,OrderStatus = 2,否则OrderStatus = OrderDetailStatus。现在,我必须列出状态值。 因此,是否可以为value语句创建别名,如下所示:
SET [Status] =
CASE (SELECT MIN(od.[Status]) FROM OrderDetail od WHERE od.OrderId = i.OrderId) AS val
WHEN 3 THEN 2
ELSE val
END
FROM INSERTED i
WHERE [Order].Id = i.OrderId
答案 0 :(得分:2)
我想“缩短”的唯一方法是:
UPDATE O
SET [Status] = CASE WHEN od.[Status] BETWEEN 3 AND 5 THEN od.[Status] - 1 ELSE od.[Status] END
FROM [Order] O
JOIN INSERTED i ON O.Id = i.OrderId
CROSS APPLY (SELECT MIN(od.[Status]) AS [Status]
FROM OrderDetail ca
WHERE ca.OrderId = i.OrderId) od;
换句话说,您应该真正避免使用保留(甚至键)字作为对象名。 ORDER
是SQL Server中的保留字,因此实际上不应该使用。 Status
是一个关键字,可以这样,但也应避免。