【问题标题】:Continue statement in while loop in TSQL?SQL中while循环中的继续语句?
【发布时间】:2010-09-27 16:00:01
【问题描述】:

在 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

【问题讨论】:

  • 我不在乎错误是什么。我需要的是我不想打破while循环。怎么样??

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


【解决方案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

【讨论】:

  • 但是有没有 continue 语句?
  • (1 行受影响)(1 行受影响)(1 行受影响)链接服务器“TEST”的 OLE DB 提供程序“SQLNCLI”返回消息“登录超时已过期”。链接服务器“TEST”的 OLE DB 提供程序“SQLNCLI”返回消息“建立与服务器的连接时发生错误。连接到 SQL Server 2005 时,此故障可能是由于在默认设置下 SQL Server 没有不允许远程连接。”。根据我的 while 循环,它应该至少运行 10 次
  • @Crawling,这个答案表明不需要继续声明,至少如您的 OP 中所述。
【解决方案2】:

在 2005 年你可以放入 try/catch。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2019-02-26
    • 2017-03-09
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多