,您的触发已经不远了,但实际上,你可以使用和INSTEAD OF触发器
创建测试数据
create table product (productId int identity(1,1) constraint PK_product_productId primary key clustered, quantity_in_stock int)
create table order_detail ( order_id int
,productId int constraint FK_order_product_productId foreign key references product (productId)
,quantity int not null)
set identity_insert product on
insert into product (productId, quantity_in_stock) values (1, 100), (2, 25) , (3, 2);
这“工作”(在长期的lossest感) 考虑到马丁的评论为quantity_in_stock
需要确定。
CREATE TRIGGER tr_check_qty
ON order_detail
FOR insert, update AS
DECLARE @stock int
DECLARE @neworder int
SELECT @stock = quantity_in_stock
From product
Where productid = (select productid from inserted)
SELECT @neworder = quantity FROM inserted
IF @neworder > @stock
BEGIN
PRINT 'NO WAY JOSE'
ROLLBACK TRANSACTION
END
这些现在都按预期工作......
INSERT order_detail (order_id, productId, quantity)
values
(10044, 1, 30) -- works as stock is 100
,(10044, 3, 1)
insert order_detail (order_id, productId, quantity)
values
(10044, 1, 130) /* fails (CORRECTLY) WITH Msg 3609, Level 16... (transacted ended in the trigger..) */
/* this should work... */
UPDATE order_detail
SET quantity = 30
WHERE order_id = 10044
AND productid = 1
/* this should fail.. */
UPDATE order_detail
SET quantity = 3000 /*< not enough stock. */
WHERE order_id = 10044
AND productid = 1
,并解决马丁斯第一点这种方式较好:
CREATE TRIGGER tr_check_qty
ON order_detail
FOR insert, update AS
DECLARE @stock int
DECLARE @neworder int
if(exists(select *
from inserted i join product p on i.productId = p.productId
where i.quantity > p.quantity_in_stock))
begin
PRINT 'NO WAY JOSE'
ROLLBACK TRANSACTION
End
感谢您的帮助@Dog Ears和@Martin!你是对的,这是一个任务:p但希望有一天我会达到一个水平,我可以为他人的家庭作业给出我自己的答案。 :D哦,是的,我有触发器工作!我在@Dog Ears的建议中提到加入产品并插入表格:DECLARE \t @stock int DECLARE \t @neworder \t int SELECT \t @stock = products.quantity_in_stock从\t产品插入WHERE products.product_id = inserted.product_id SELECT \t @neworder = inserted.quantity从\t插入触发器工作!再次感谢您的回复!^_^ – Magi604 2010-12-04 07:37:05