0

在 Sql Server 2000 和 2005 中,我在 while 循环中运行 select 语句。JFYI,这个选择语句连接到许多链接的服务器并获取一些值。

如果有任何错误,我希望它仍应在循环中执行下一条语句(类似于 c# 中的 continue 语句)

例子:-

while @rowcount < 10
begin
 set @sql = 'select * from <Remotemachine>.db1.dbo.table1'
 exec sp_executesql @sql
 set @rowcount = @rowcount +1
End
4

2 回答 2

1

从这里开始:http: //www.sommarskog.se/error_handling_2005.html

请记住,一些错误是会话甚至是批处理终止符,您无法捕获这些错误

我给您的链接(以及该页面上的 2 个链接)应该为您提供有关如何处理此问题的足够信息

顺便说一句,除非它是不可捕获的错误,否则它将继续执行

运行这个

declare @rowcount int, @sql nvarchar(100)
set @rowcount = 1
while @rowcount < 10
begin
 set @sql = 'select * from <Remotemachine>.db1.dbo.table1'
 exec sp_executesql @sql
 print @rowcount
 set @rowcount = @rowcount +1
End

这是输出

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
1
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
2
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
3
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
4
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
5
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
6
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
7
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
8
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '<'.
9

这是您可以TRY CATCH用来捕获此问题的方法

declare @rowcount int, @sql nvarchar(100)
set @rowcount = 1
while @rowcount < 10
begin
 set @sql = 'select * from <Remotemachine>.db1.dbo.table1'

 begin try 
      exec sp_executesql @sql
 end try 
 begin catch
      select ERROR_MESSAGE() -- or do something
 end catch
 print @rowcount
 set @rowcount = @rowcount +1
End
于 2010-09-27T16:03:39.800 回答
1

在 2005 年,您可以使用 try/catch。

于 2010-09-27T16:04:25.010 回答