从这里开始: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