Sql server。当前事务无法提交,也无法支持写入日志文件的操作

时间:2018-01-31 15:49:57

标签: sql-server tsql transactions

{County: "Cork"}
{County: "Roscommon"}

我可以做什么来提交交易? 我知道,begin tran begin try select case when 1=0 then 0.0 else '' end --this will not work end try begin catch --error has occured. But it doesnt matter. We want to continue anyway end catch select 1 --do something else commit --unfortunatelly this producess error "The current transaction cannot be committed and cannot support operations that write to the log file" 是不正确的。这就是为什么它在try / catch块中(在实际情况下这是由管理员定义的查询)。但我想做其余的操作。

编辑:// 如果“不正确的查询”是例如select case when 1=0 then 0.0 else '' end

,则代码可以正常工作
select 1/0

2 个答案:

答案 0 :(得分:0)

来自this page

"如果在TRY块中生成的错误导致当前事务的状态无效,则该事务被分类为不可提交的事务。通常在TRY块之外结束事务的错误会导致事务在TRY块内发生错误时进入不可提交状态。不可提交的事务只能执行读操作或ROLLBACK TRANSACTION。"

来自this page

" SQL Server可以容忍事务内部的一些错误,而不必将其标记为不可提交。例如,SELECT 1/0会导致错误,但不会强制事务进入不可提交状态。"

答案 1 :(得分:0)

您可以在提交或退出之前尝试检查事务状态。

begin tran
begin try
    select case when 1=0 then 0.0 else '' end --this will not work
end try
begin catch
--error has occured. But it doesnt matter. We want to continue anyway
end catch

select 1 --do something else

IF (XACT_STATE()) = -1
    rollback tran
IF (XACT_STATE()) = 1
    commit tran