日期:2014-05-19  浏览次数:20629 次

存储过程中,也要加入commit吗?
CREATE   procedure   xxx
@xxx   nvarchar(15)
as
set   nocount   on

update   xxx   set   xxx=1   where   xxx=@xxx


begin
        if   exists(select   top   1   id   from   xxx   where   xxx=@xxx)
            update   xxx  
                set  
                        xxx1=getdate(),                  
                        xxx=xxx
                where  
                        xxx=@xxx
        else
              insert   into   xxx(xxx)  
              values(@xxx)    
end

GO
请教大侠们:
1.有必要加commit吗?如果不加,会出什么问题?
2.如果要应该在哪些地方加合适?

谢谢!


------解决方案--------------------
CREATE procedure xxx
@xxx nvarchar(15)
as

set nocount on

set xact_abort on


begin tran

update xxx set xxx=1 where xxx=@xxx


begin
if exists(select top 1 id from xxx where xxx=@xxx)
update xxx
set
xxx1=getdate(),
xxx=xxx
where
xxx=@xxx
else
insert into xxx(xxx)
values(@xxx)
end

commit tran

return 0
go
------解决方案--------------------
commit和begin是成对的,另:你就一个原子语句,没必要加
------解决方案--------------------
最好加事务,以确保要么全成功,要么全失败,避免一半成功一半失败的情况.
把更新和插入或删除操作放到一个事务中就可以了.
------解决方案--------------------
根據自己的需要來定義事務的大小。然後再每個事務commit,rollback
------解决方案--------------------
CREATE procedure xxx
@xxx nvarchar(15)
as
set nocount on
begin tran
update xxx set xxx=1 where xxx=@xxx
if @@error <> 0 goto error

if exists(select top 1 id from xxx where xxx=@xxx)
update xxx
set
xxx1=getdate(),
xxx=xxx
where
xxx=@xxx
else
insert into xxx(xxx)
values(@xxx)

if @@error <> 0 goto error
commit
return

error:
rollback

------解决方案--------------------
CREATE procedure xxx
@xxx nvarchar(15)
as
set nocount on
BEGIN TRANSACTION /*开始事务*/
update xxx set xxx=1 where xxx=@xxx
if @@error <> 0
begin
raiserror( '抱歉,更新时发生错误,更新失败! '16,1)
ROLLBACK /*回滚,取消修改*/
return
end
if exists(select 1 from xxx where xxx=@xxx)
begin
update xxx set xxx1=getdate(), xxx=xxx
where xxx=@xxx
if @@error <> 0
begin
raiserror( '抱歉,更新时发生错误,更新失败! '16,1)
ROLLBACK /*回滚,取消修改*/
return
end