Sql 具有输入参数的存储过程内的事务

Sql 具有输入参数的存储过程内的事务,sql,sql-server,tsql,stored-procedures,Sql,Sql Server,Tsql,Stored Procedures,我的存储过程工作正常,但问题是它没有检查 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-@Quan

我的存储过程工作正常,但问题是它没有检查

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
条件

如果我的输入数量大于特定产品的数量,则数据仅插入到product_Sales表中。但如果条件
(quantity-@quantity)>0
失败,则事务将回滚,但它正在提交事务。为什么?如何解决此问题?

ALTER Procedure[dbo].[usp\u Update\u Quantity]--0
(quantity - @quantity) > 0 
回滚事务 打印“操作未成功” 端接 结束
更改程序[dbo]。[usp\u更新\u数量]--0
回滚事务
打印“操作未成功”
端接
结束

旁注:您不应该在存储过程中使用
sp
前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用
sp.
并使用其他东西作为前缀,或者根本不使用前缀!在你的程序中没有什么会引起错误的。它将计算where子句,找到满足这些条件的0行,更新0行,然后继续。我认为您不仅仅是在用Product\u ID=参数值(可能是您想要的)更新行,而是在表中包含传递的Product\u ID参数的情况下,用QUOTE>@QUOTE更新所有行!!!下面穆罕默德·阿里的回答似乎解决了这个问题。旁注:您不应该在存储过程中使用
sp.
前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用
sp.
并使用其他东西作为前缀,或者根本不使用前缀!在你的程序中没有什么会引起错误的。它将计算where子句,找到满足这些条件的0行,更新0行,然后继续。我认为您不仅仅是在用Product\u ID=参数值(可能是您想要的)更新行,而是在表中包含传递的Product\u ID参数的情况下,用QUOTE>@QUOTE更新所有行!!!下面穆罕默德·阿里的回答似乎解决了这个问题。
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