【发布时间】:2017-08-04 01:10:00
【问题描述】:
我正在尝试为数据库设置触发器(我正在使用 Microsoft SQL Server)。
我有两张桌子
create table atbv_Sales_Products
(
ProductID integer,
TotalQuantity integer
);
insert into atbv_Sales_Products values (1, 1);
insert into atbv_Sales_Products values (2, 2);
insert into atbv_Sales_Products values (3, 20);
insert into atbv_Sales_Products values (4, 10);
insert into atbv_Sales_Products values (5, 20);
insert into atbv_Sales_Products values (6, 10);
insert into atbv_Sales_Products values (7, 5);
insert into atbv_Sales_Products values (8, 50);
insert into atbv_Sales_Products values (9, 1);
create table atbv_Sales_OrdersLines
(
OrderID integer,
ProductID integer,
Amount integer
);
insert into atbv_Sales_OrdersLines values (6, 4, 1);
insert into atbv_Sales_OrdersLines values (6, 6, 1);
insert into atbv_Sales_OrdersLines values (6, 1, 1);
insert into atbv_Sales_OrdersLines values (47, 4, 1);
insert into atbv_Sales_OrdersLines values (6, 9, 1);
insert into atbv_Sales_OrdersLines values (5, 7, 1);
insert into atbv_Sales_OrdersLines values (6, 2, 2);
还有一个插入表(它实际上是自动生成的,但为了清楚起见我们把它放在这里
create table Inserted
(
OrderID integer,
ProductID integer,
Amount integer
);
insert into Inserted values (48, 4, 9);
insert into Inserted values (48, 1, 10);
insert into Inserted values (48, 8, 100);
insert into Inserted values (48, 2, 1);
为了更容易理解,这里是这些表格的图形外观:
产品表
OrdersLines 表
插入表格
现在触发器应该检查插入的金额值 + 之前的金额值是否超过 TotalQuantity(这是一个静态值。或者换句话说,当新订单进来时它不会改变),如果是则回滚更改
为了过滤我使用这部分代码
IF EXISTS (select p.ProductID
from atbv_Sales_Products p
join Inserted i
on p.ProductID = i.ProductID
join atbv_Sales_OrdersLines ol
on p.ProductID = i.ProductID
group by i.ProductID, i.Amount, p.TotalQuantity
having (SUM(ol.Amount) + i.Amount) > p.TotalQuantity)
然后我一直在尝试使用代码的以下代码部分来回滚更改并警告错误
BEGIN
DECLARE @ProductID NVARCHAR(60)
SET @ProductID = (SELECT p.ProductID
FROM atbv_Sales_Products p
JOIN inserted i
ON i.ProductID = p.ProductID)
RAISERROR ('----There is not enough items number (%s) left----', 18, 1, @ProductName) ROLLBACK TRANSACTION
RETURN
END
如果只有一个插入行,这很好,但我不知道如果像当前示例中那样有多行,该怎么办。我想我已经在某个地方读过我可以创建一个临时表,但同样,不知道如何将那些被代码的第一部分过滤掉的值插入其中,然后使用这些值显示在错误消息中。
【问题讨论】:
-
您是否只想要一个不同的产品 ID 列表,用逗号分隔?
-
@Xedni 我想在错误消息和回滚更改中显示超过 TotalQuantity 的产品 ID,因为它们无法应用(第二部分由
ROLLBACK TRANSACTION
标签: sql-server tsql