ALTER Procedure [dbo].[sp_Update_Quantity]
(
@Quantity INT,
@Product_ID INT
)
AS
BEGIN
begin try
Begin Transaction
update Product
Set Product.Quantity=(Product.Quantity-@Quantity)
where (Product.Quantity-@Quantity>0)
AND @Product_ID IN (Select Product_ID from Product)
insert into Product_Sales(Product_ID,Quantity)
values(@Product_ID,@Quantity)
commit Transaction
print 'Successfull Inserted'
end try
begin catch
Rollback Transaction
print 'Operation is not Successfull'
end catch
END
我的存储过程工作正常,但问题是它没有检查
(quantity - @quantity) > 0
条件。
如果我的输入数量大于特定产品数量的数量,则仅插入到Product_Sales表中。但是我想如果条件(quantity - @quantity) > 0
失败,则事务将回滚,但它正在提交事务。为什么?如何解决问题?
答案 0 :(得分:1)
ALTER Procedure [dbo].[usp_Update_Quantity] --<--- See explanation by marc_s in your comments
( -- about using sp prefix for your procs
@Quantity INT,
@Product_ID INT
)
AS
BEGIN
begin try
DECLARE @Stock INT;
SELECT @Stock = Product.Quantity
FROM Product
WHERE Product_ID = @Product_ID
IF (@Stock < @Quantity)
BEGIN
RAISERROR('Not Enough Stock', 16, 1)
RETURN
END
Begin Transaction
update Product
Set Product.Quantity=(Product.Quantity-@Quantity)
where Product_ID = @Product_ID
insert into Product_Sales(Product_ID,Quantity)
values(@Product_ID,@Quantity)
commit Transaction
print 'Successfull Inserted'
end try
begin catch
IF @@ROWCOUNT > 0
Rollback Transaction
print 'Operation is not Successfull'
end catch
END