Reputation: 505
I have created the following trigger so that if any item in the Sales.OrderDetails table has a unitprice less than 10, it cannot have a discount greater than .5:
create trigger Sales.tr_SalesOrderDetailsDML
on Sales.OrderDetails
After insert, update
as
begin
if @@ROWCOUNT > 0 return ;
set nocount on;
if exists (select oi.orderid
from inserted as oi
where oi.unitprice < 10.0 and oi.discount > 0.50)
Throw 50002, 'Order can''t have discount more than 5 if unit price is less than 10', 10;
end;
go
When I insert the following row:
INSERT INTO Sales.OrderDetails (orderid,productid,unitprice,qty,discount)
VALUES (10249, 16, 9.00, 1, 0.90);
it accepts it, the trigger does not Throw the error despite the fact that it's unitprice is less than 10 and decount is bigger than 5.
What am I missing here?
Upvotes: 1
Views: 179
Reputation: 82474
You have multiple mistakes here.
after
trigger. meaning it will only be executed after the row was already inserted or updated.if @@ROWCOUNT > 0 return;
Alter your table to add a check constraint that will prevent the value of discount to be bigger then 5 when the unit price is less then 10.
ALTER TABLE Sales.OrderDetails
ADD CONSTRAINT CHK_UnitPriceAndDiscount
CHECK (unitprice > 10 OR discount < 0.5)
GO
Upvotes: 3
Reputation: 1136
it's not do statement under if @@ROWCOUNT > 0 return ;
because @@rowcount
greater than 0 then it return
Upvotes: 1
Reputation: 8867
Check this line if @@ROWCOUNT > 0 return ;
This will return immediately if affected rows is greater than 0... so the additional logic will not be executed. Replace with if @@ROWCOUNT = 0
Upvotes: 1