我需要创建视图或过程,从50个链接的服务器中选择一些数据,但其中一些可以脱机(糟糕的互联网)。
我有这段代码
declare @srvr nvarchar(128), @retval int;
set @srvr = 'SERVER103';
begin try
exec @retval = sys.sp_testlinkedserver @srvr;
end try
begin catch
set @retval = sign(@@error);
end catch;
if @retval = 0
select sel1.sum1, sel1.sum2, sel2.sum1, sel2.sum2 from
(select sum(column1) as sum1, sum(column2) as sum2 from [SERVER103].[dbo].[table] where date like '201702%' group by column1, column2) as sel1
(select sum(column1) as sum1, sum(column2) as sum2 from [SERVER103].[dbo].[table2] where date like '201702%' group by column1, column2) as sel2
但它仍然会引起连接错误并打破整个脚本。 接下来我需要它必须通过所有链接服务器和联合结果成为一个重要结果。
有什么想法吗? 感谢
答案 0 :(得分:0)
以下代码使用游标遍历每个链接服务器。如果连接良好,则添加动态sql,否则打印消息。结束动态sql仅适用于良好的链接:
declare @loop as int=1
declare @srvname as nvarchar(100)
declare @sql as nvarchar(max)=N''
declare @Date as varchar(10) = '201702%'
declare srvcursor cursor for select srvname from sysservers where srvname <> @@SERVERNAME
open srvcursor
fetch next from srvcursor into @srvname
WHILE @@FETCH_STATUS = 0
begin
begin try
exec sys.sp_testlinkedserver @srvname
set @sql=@sql+N'select sel1.sum1, sel1.sum2, sel2.sum1, sel2.sum2 from
(select sum(column1) as sum1, sum(column2) as sum2 from [' + @srvname + N'].[dbo].[table] where date like ''' + @Date + N''' group by column1, column2) as sel1
(select sum(column1) as sum1, sum(column2) as sum2 from [' + @srvname + N'].[dbo].[table2] where date like ''' + @Date + N''' group by column1, column2) as sel2
UNION '
end try
begin catch
print @srvname + 'is broken.'
end catch
fetch next from srvcursor into @srvname
end
if @sql <> N''
begin
set @sql = left(@sql, len(@sql)-6)
print @sql
--exec(@sql)
end
close srvcursor
deallocate srvcursor