March 15, 2012 at 10:31 am
create table product1
(
productid int,
productname varchar(20),
costprice int,
sellingprice int
)
My trigger should not allow to insert such a DATA whose costprice is greater then sellingprice.
create trigger abcd1
on product1 for insert
as
select @cp = costprice, @sp-2 = sellingprice from inserted
rollback tran
-following insert command, data donot insert but show an error
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
insert into product1 values('3','cup', 34,21)
--following insert command data will insert but still show an error
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
insert into product1 values('4','mouse', 50,51)
March 15, 2012 at 10:38 am
Why not use a table constraint where SellingPrice > CostPrice?
March 15, 2012 at 10:38 am
first, you don't need a trigger...you could simply add a check constraint to prevent that.
ALTER TABLE product1 ADD CONSTRIANT CK_COST_VS_SELL CHECK(costprice <= sellingprice)
your trigger assumes only one row being inserted, instead, it should check all rows in the insert, and reject the insert if even one mistake exists.
create trigger abcd1
on product1 for insert
as
if EXISTS(SELECT 1 FROM inserted WHERE costprice > sellingprice)
rollback tran
Lowell
March 15, 2012 at 10:42 am
Thanks, it work with constraint.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply