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