如果Notes表中不存在某个元素,那么之前的插入行应该回滚。我想通过将两行放在Begin事务中,它会回滚,但由于没有抛出错误,它会执行insert命令。如果不存在元素,如何抛出错误,以便回滚整个代码块?
begin try
begin transaction
insert into notes (memberid, NoteEffDate, LoginName, NoteDesc) values (367737, GETDATE(), 'marc', 'blah blah')
IF EXISTS (SELECT memberid FROM notes WHERE memberid =4774769)
begin
update notes set notedesc = 'hello there' where memberid = 4774769
end
commit transaction
end try
begin catch
rollback transaction
select ERROR_MESSAGE()
end catch
go
答案 0 :(得分:1)
您似乎正在尝试使用某些版本的Sam Saffron's upsert method。
程序的粗略版本:
create procedure dbo.notes_upsert (
@memberid int
, @notesdesc varchar(256)
, @loginname varchar(256)
) as
begin
set nocount on;
set xact_abort on;
begin tran
update notes (with serializable)
set notedesc = @notedesc
where memberid = @memberid;
if @@rowcount = 0
begin;
insert into notes (memberid, NoteEffDate, LoginName, NoteDesc)
values (@memberid, getdate(), @loginname, @notesdesc);
end;
commit tran
end;
答案 1 :(得分:1)
您可能尝试阻止中的RaiseError。
begin try
begin transaction
insert into notes (memberid, NoteEffDate, LoginName, NoteDesc) values (367737, GETDATE(), 'marc', 'blah blah')
IF EXISTS (SELECT memberid FROM notes WHERE memberid =4774769)
begin
update notes set notedesc = 'hello there' where memberid = 4774769
end
ELSE
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
commit transaction
end try
begin catch
rollback transaction
select ERROR_MESSAGE()
end catch
go