我想更改我的存储过程,以便它在无法连接到链接服务器后继续执行。我怎样才能更好地编写这个存储过程?
我正在使用 TRY...CATCH 来查询我正在从列表中创建的服务器,以跟踪事务日志备份历史记录。
ALTER PROC [dbo].[spLogBackup]
AS
TRUNCATE TABLE dbo.tLogBackup
DECLARE servers_cursor CURSOR
FOR
select distinct LinkedserverName
from dbo.Environment
join master..sysservers on srvname COLLATE DATABASE_DEFAULT =
LinkedserverName COLLATE DATABASE_DEFAULT
where LinkedServerName not in ('TestDB')
and ServerUse in ('PROD', 'DR')
and IncludeInstats = 1
order by LinkedServerName
OPEN servers_cursor
DECLARE @Servername varchar(250)
DECLARE @sql varchar(8000)
FETCH NEXT FROM servers_cursor INTO @ServerName
WHILE (@@FETCH_STATUS = 0)
BEGIN TRY
--Looping throught the servers.
set @sql = 'insert into dbo.tLogBackup (servername, rundate, runtime,
jobname, Status, CurrentStatus, enabled) select ''' + @ServerName +
''',last_run_date, last_run_time, name, last_run_outcome,
current_execution_status, enabled
from openquery([' + @ServerName + '],''exec
msdb.dbo.sp_get_composite_job_info'' )'
print @ServerName
exec (@sql)
--SELECT (@sql)
FETCH NEXT FROM servers_cursor INTO @ServerName
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
CLOSE servers_cursor
DEALLOCATE servers_cursor
您只需要为 WHILE LOOP 添加 BEGIN/END 并将 FETCH NEXT 移到 TRY/CATCH 之外