在存储过程中使用try catch可以回滚么?如何加事务?是用try catch还是用tran

xin_shui 2008-06-12 10:16:25
现在存储过程里有多个删除添加操作,如:
select* from A
delect * from B
insert * from B
那如果我添加事务的话是不是如下:
begin try
select* from A
delect * from B
insert * from B
end try
begin catch
end catch
这样可以全部回滚么?和用tran有什么区别?
...全文
726 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xin_shui 2008-06-20
  • 打赏
  • 举报
回复
我现在是这样写的:
begin try
begin tran
T-SQL语句
commit tran
end try
begin catch
rollback
end catch
我在sql里面做了一个错误,然后一下子就把表锁住了,我不知道该怎么写
xin_shui 2008-06-12
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wzy_love_sly 的回复:]
SQL codecreatetable表a(namevarchar(20)notnull)createtable表b(namevarchar(20))begintrybegintraninsertinto表aselect'a'insertinto表bselect'c'committranendtrybegincatchrollbackendcatch--全部插入begintrybegintraninsertinto表aselectnullinsertinto表bselect'c'committranendtrybegincatchrollbackendcatch--全部回滚select*from表aselect*from表b
[/Quote]

为什么有错的时候就锁死呢,会不会别的地方有错误
  • 打赏
  • 举报
回复
begin try
begin tran
T-SQL语句
commit tran
end try
begin catch
错误处理
end catch

begin try只有T-SQL语句出现错误的时候,才进行错误处理的。
xin_shui 2008-06-12
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wzy_love_sly 的回复:]
SQL codecreatetable表a(namevarchar(20)notnull)createtable表b(namevarchar(20))begintrybegintraninsertinto表aselect'a'insertinto表bselect'c'committranendtrybegincatchrollbackendcatch--全部插入begintrybegintraninsertinto表aselectnullinsertinto表bselect'c'committranendtrybegincatchrollbackendcatch--全部回滚select*from表aselect*from表b
[/Quote]
我是这样写的,insert的时候我做了一个错误的,但是一下子就锁死了。
M1CR0S0FT 2008-06-12
  • 打赏
  • 举报
回复
都不严谨,提交或者回滚事务,都需要考虑对事务数和XACT_STATE()的判断.
xin_shui 2008-06-12
  • 打赏
  • 举报
回复
这样写
begin try
select* from A
delect * from B
insert * from B
end try
begin catch
rollback
end catch
可以么?
wzy_love_sly 2008-06-12
  • 打赏
  • 举报
回复
create table 表a(name varchar(20) not null)
create table 表b(name varchar(20))

begin try
begin tran
insert into 表a select 'a'
insert into 表b select 'c'
commit tran
end try
begin catch
rollback
end catch
--全部插入

begin try
begin tran
insert into 表a select null
insert into 表b select 'c'
commit tran
end try
begin catch
rollback
end catch
--全部回滚

select * from 表a
select * from 表b
xin_shui 2008-06-12
  • 打赏
  • 举报
回复
那我该怎么写呢?
  • 打赏
  • 举报
回复
tran是事务
catch try表是的意思是获取事务执行过程中的错误,并进行相应的处理

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧