2010-09-27 84 views
0

在Sql Server 2000和2005中,我在while循環中運行select語句。 JFYI,這個select語句連接到許多鏈接的服務器並獲取一些值。在TSQL中的while循環中繼續聲明?

如果有任何錯誤,我想應該還是在循環中執行下一條語句(類似於繼續在C#中的語句)

例子: -

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

我不在乎錯誤是什麼。我需要的是我不想打破while循環。怎麼樣?? – Jango 2010-09-27 16:09:44

回答

1

從這裏開始:http://www.sommarskog.se/error_handling_2005.html

請記住,有些錯誤是會話甚至批終止符,你不能捕獲這些錯誤

我給你的鏈接(和2個鏈接該網頁上)應該給你如何BTW處理這個

足夠的信息,除非它是一個非trapable錯誤,否則它將繼續執行

來看,這種

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

但是有沒有繼續聲明? – Jango 2010-09-27 16:06:41

+0

(1 row(s)affected) (1 row(s)affected) (1 row(s)affected) 鏈接服務器「TEST」的OLE DB提供程序「SQLNCLI」返回消息「登錄超時已過期」。 對於鏈接服務器「TEST」OLE DB提供程序「SQLNCLI」返回的消息「建立與服務器的連接時發生錯誤。連接到SQL Server 2005時,此故障可能是由於在默認設置下SQL Server不允許遠程連接。「 根據我的while循環,它應該至少運行10次 – Jango 2010-09-27 16:16:11

+0

@抓取,這個答案表明的是沒有必要使用continue語句,至少在OP中有說明。 – 2010-09-27 16:17:47

1

2005年,您可以放入一個try/catch。