views:

37

answers:

2

Hi, In Sql Server 2000 and 2005 I am running a select statement in a while loop. JFYI, this select statement is connecting to many linked servers and getting some values.

IF there is any error, i want it should still execute next statement in the loop (similar to continue statement in c#)

Example:-

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

Start here: http://www.sommarskog.se/error_handling_2005.html

Keep in mind that some errors are session and even batch terminators and you can't trap those

The link I gave you(and the 2 links on that page) should give you enough information on how to handle this

BTW, unless it is a non trapable error it will continue executing

run this

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

Here is the output

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

Here is how you can use TRY CATCH to trap this

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
SQLMenace
but is there any continue statement?
Novice
(1 row(s) affected)(1 row(s) affected)(1 row(s) affected)OLE DB provider "SQLNCLI" for linked server "TEST" returned message "Login timeout expired".OLE DB provider "SQLNCLI" for linked server "TEST" returned message "An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.".It should run at least 10 times according to my while loop
Novice
@Crawling, what this answer demonstrates is there isn't a need for a continue statement, at least as stated in your OP.
Ralph Shillington
@Ralph: Oke. But I am getting error and my loop execution breaks..
Novice
Added a 2nd codeblock that should trap the error
SQLMenace
You are AWESOME SQlMenace. Thanks very much..
Novice
+1  A: 

In 2005 you can put in a try/catch.

Noel Abrahams