有关名称延迟解析的问题

bala7229291 2011-04-18 03:55:35
为了说明问题,我先做一些表来模拟

--创建测试表test
create table test(a int, b int)
go

create table test1(a int, b int)
go

--插入测试数据
insert into test
select 1, 2 union all
select 2, 2 union all
select 3, 2 union all
select 4, 2
go

insert into test1
select 1, 3 union all
select 2, 3 union all
select 3, 3 union all
select 4, 3
go

--创建测试存储过程
create proc sp_test
as
begin
set transaction isolation level repeatable read
begin tran
begin try
select *
from test

select *
from test1 --此表不存在,名称延迟解析
commit tran
end try
begin catch --catch是不能抛出名称延迟解析的错误以及编译错误
rollback tran
return (1)
end catch

return (0)
end



由于业务需要test1表被意外的修改为test2

新建一个查询窗口,执行存储过程,就会出现名称延迟解析的错误,且没有被catch捕获,导致事务不能提交,保持打开状态
可以用一下代码模拟

exec sp_test


由于事务属于repeatable read 级别,被查询的test表记录将被(共享锁)锁定着,会造成其他访问test的修改的表一直等待着
如:

update test
set b = 6
from test


我的问题是,怎么能在存储过程里避免出现这种未提交的事务产生
...全文
77 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
bala7229291 2011-04-19
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 rucypli 的回复:]
begin tran
begin try
select *
from test
if @@error>0 rollback tran
select *
from test1 --此表不存在,名称延迟解析
if @@error>0 rollback tran
commit tran
[/Quote]
那些if语句根本就没用,程序都不运行到if那里,rollback不起作用的,这位同学就没看懂我的例子吧
rucypli 2011-04-18
  • 打赏
  • 举报
回复
begin tran
begin try
select *
from test
if @@error>0 rollback tran
select *
from test1 --此表不存在,名称延迟解析
if @@error>0 rollback tran
commit tran
bala7229291 2011-04-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 jinfengyiye 的回复:]
延迟应该在下一次运行时会报错。怎么会不能更新?
[/Quote]

因为两次相当与两个事务, 第一个事务用了共享锁把test的记录锁定,在查询test1的时候因为找不到对象的执行错误,存储过程不会再往下执行,第一个事务就始终打开,test的记录始终被锁定, 当第二个事务去更新的时候,发现test的记录被上锁,只能等待,因为test记录不会再提交或者回滚,因此第二个事务就一直等待
bala7229291 2011-04-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ap0405140 的回复:]
事务中在使用表名之前,先判断该表是否存在.

SQL code

IF OBJECT_ID('[表名]') IS NOT NULL
[存在时的代码]
ELSE
[不存在时的代码]
[/Quote]

嗯,这个办法确实可以,解决了表名的解析的情况,还有没有其他更好点的办法
gw6328 2011-04-18
  • 打赏
  • 举报
回复
延迟应该在下一次运行时会报错。怎么会不能更新?
唐诗三百首 2011-04-18
  • 打赏
  • 举报
回复
事务中在使用表名之前,先判断该表是否存在.

IF OBJECT_ID('[表名]') IS NOT NULL
[存在时的代码]
ELSE
[不存在时的代码]

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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