在SQL中的while循环中继续语句?

时间:2010-09-27 16:00:01

标签: sql sql-server sql-server-2005 tsql oracle-sqldeveloper

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

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

实施例: -

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

2 个答案:

答案 0 :(得分:1)

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

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

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

BTW,除非它是一个非陷阱错误,它将继续执行

运行此

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

答案 1 :(得分:1)

2005年你可以试一试。