【问题标题】:SQL server RollbackSQL 服务器回滚
【发布时间】:2014-04-29 21:48:25
【问题描述】:

我创建了一个事务过程,除了由于某种原因回滚一直显示其错误消息并且它不允许插入正常运行之外,它都可以正常工作。所以现在我不确定当我注释掉该部分时我需要做些什么来解决这个问题它一切正常它只是 IF 回滚语句

Create Proc DP_Transaction
    @PartNumber Varchar (10)= NULL,
    @PartDescription Varchar(50) = Null,
    @ReorderLevel Decimal(5,0) =Null,
    @StockLevel decimal(5,0)= null,
    @StockOnOrder decimal(5,0) =null
as  

If @PartNumber IS NULL
begin
Print 'You must enter something for Partnumber' 
Print 'Order Not Processed'
print ' '
return
end

If @PartDescription IS NULL
 begin
Print 'You must enter something PartDescription' 
Print 'Order Not Processed'
print ' '
return
 end

If @ReorderLevel IS NULL
begin
Print 'A number must entered for ReorderLevel' 
Print 'Order Not Processed'
print ' '
return
end


If @StockLevel is Null 
Begin
print 'A number must be entered for StockLevel'
print 'Order Not Processed'
Print ''
Return
End

If @StockOnOrder is null
Begin
Print 'A number must be entered for StockOnOrder'
Print 'Order Not Processed'
Print ''
Return
End

Begin Transaction
Insert into InventoryPart
(Partnumber,PartDescription,ReorderLevel,StockLevel,StockOnOrder)
 Values(@PartNumber,@PartDescription,@ReorderLevel, @StockLevel, @StockOnOrder)


//This is where I am having the errors
If exists (Select PartNumber from InventoryPart where PartNumber = @PartNumber)
Begin
Print ' The Partnumber ' + @PartNumber+' is already in the InventoryPart table'
print ' you must select a different PartNumber'
Print ' Item not inserted'
print ''
Rollback

end
else

begin
Commit Transaction
print 'Part has been added'
print ''
print ''
End

【问题讨论】:

    标签: sql sql-server transactions procedure rollback


    【解决方案1】:

    您的查询不会向表中添加任何部分。当您检查上一条语句中插入的部分是否存在时,它将始终为真,因此始终Rollback您的事务。

    在您的示例中使用事务是没有意义的。您只需使用IF-ELSE 即可完成此操作。

    在我看来,事务只应在绝对需要时使用。
    这里你只是想INSERT 一个零件IF 它在表格中不存在,ELSE 你正在显示一条消息。

    IF EXISTS (Select 1 from InventoryPart where PartNumber = @PartNumber)
    BEGIN
        /*What you need to do*/
    END
    ELSE 
    BEGIN
        /*What you need to do*/
    END
    

    【讨论】:

    • 是的,交易是这种特殊情况的要求。但是非常感谢您的帮助,我的问题得到了解决!
    • 还有一点,当您运行Select PartNumber from InventoryPart where PartNumber = @PartNumber 时,它会返回true,因为您之前的插入查询结果在当前事务中是可见的。您需要先检查它,然后插入或回滚,就像 @user2989408 所做的那样。
    【解决方案2】:

    看来,插入语句创建的记录在此过程中总是会回滚,因为您在插入后检查记录是否存在。你可以通过使用类似的东西来解决这个问题

    -- replaces your transaction block:
    -- only run insert if no record already exists
    IF NOT EXISTS (Select * FROM InventoryPart where PartNumber = @PartNumber)
    BEGIN
       INSERT INTO InventoryPart ....
    END;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2010-09-30
      • 1970-01-01
      相关资源
      最近更新 更多