我有存储过程,我有一个交易。
当我使用SQL Server管理工作室执行它时没有错误,但是当我使用我的C#代码执行它时,会发生以下错误:
ROLLBACK TRANSACTION请求没有相应的BEGIN TRANSACTION
代码是:
CREATE PROCEDURE [dbo].[AddHardDisk]
@name nvarchar(50), @brand nvarchar(50), @serial nvarchar(50), @cost float, @seller nvarchar(50),@note nvarchar(1000),@buyDate Date,
@size int ,@moneyType nvarchar(50)
AS
DECLARE @addedDeviceID int
BEGIN TRY
BEGIN TRAN
insert into Product(Name,Brand,Serial,Cost,Seller,Note,MoneyType,BuyDate)
values(@name,@brand,@serial,@cost,@seller,@note,@moneyType,@buyDate)
select @addedDeviceID =SCOPE_IDENTITY()
insert into HardDisk(ID,size)
values(@addedDeviceID,@size)
exec DecreaseMoneyFromFund @moneyType,@cost
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
答案 0 :(得分:1)
TRAN的范围是你的TRY块,所以在你回滚的catch中它不存在。切换它:BEGIN TRAN 然后开始尝试。
回滚必须在事务范围内发生,而不是在事务之前或之后。修改后的代码:
CREATE PROCEDURE [dbo].[AddHardDisk]
@name nvarchar(50), @brand nvarchar(50), @serial nvarchar(50), @cost float, @seller nvarchar(50),@note nvarchar(1000),@buyDate Date,
@size int ,@moneyType nvarchar(50)
AS
DECLARE @addedDeviceID int
BEGIN TRAN
BEGIN TRY
insert into Product(Name,Brand,Serial,Cost,Seller,Note,MoneyType,BuyDate)
values(@name,@brand,@serial,@cost,@seller,@note,@moneyType,@buyDate)
select @addedDeviceID =SCOPE_IDENTITY()
insert into HardDisk(ID,size)
values(@addedDeviceID,@size)
exec DecreaseMoneyFromFund @moneyType,@cost
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
END TRAN
答案 1 :(得分:0)
这是我用于Sp的空壳。我想你可能会错过'Commit Tran'
BEGIN TRY ;
BEGIN TRAN;
BEGIN
--Insert SQL Here
END
IF @@TRANCOUNT > 0
COMMIT TRAN ;
END TRY
BEGIN CATCH ;
DECLARE @ERROR_MESSAGE VARCHAR(200) ;
DECLARE @ERROR_SEVERITY INT ;
DECLARE @ERROR_STATE INT ;
SET @ERROR_MESSAGE = ERROR_MESSAGE() ;
SET @ERROR_SEVERITY = ERROR_SEVERITY() ;
SET @ERROR_STATE = ERROR_STATE() ;
RAISERROR ( @ERROR_MESSAGE, -- Message text.
@ERROR_SEVERITY , -- Severity.
@ERROR_STATE -- State.
);
Select @ERROR_MESSAGE
IF @@TRANCOUNT > 0
ROLLBACK TRAN ;
END CATCH ;