簡體   English   中英

存儲過程中帶有輸入參數的事務

[英]Transaction inside stored procedure with input parameter

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失敗,則交易將回滾,但它將提交交易。 為什么? 如何解決問題?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM