How to query against multiple linked servers?

一世执手 提交于 2021-02-07 18:23:25

问题


After linking some SQL Server 2008 Servers / instances, I would like to do a more generic query against these servers. I know that I must specify the destiny of the query like that:

select * 
from [SRV\INSTANCE].dbname.dbo.foo

But, I would run this query against more than one linked server. I know also that this select statement returns exactly the SRV\INSTANCE that I need:

select ss.name 
from sys.servers ss 
where ss.server_id > 0

This one, returns all servers\instances from where I want query against to.

At this scenario, all databases have the same structure, so I wanted to do something like this:

select * 
from [select ss.name from sys.servers ss where ss.server_id > 0].DBNAME.dbo.foo

Any ideas?

Thanks in advance.


回答1:


You can dynamically create SQL statement on the fly and then run that command. In this scenario in @dml variable with help += operator the whole command dynamically is created

DECLARE @dml nvarchar(max) = N''
SELECT @dml += 'UNION ALL SELECT * FROM ' + QUOTENAME(ss.name) + 
               '.[DBNAME].[dbo].foo ' 
FROM sys.servers ss
WHERE ss.server_id > 0

SELECT @dml = STUFF(@dml, 1, 10, '')
EXEC sp_executesql @dml



回答2:


That requires a dynamic query, like:

declare @servers table (name sysname)

insert  @servers
        (name)
select  name
from    sys.servers
where   server_id > 0

declare @query nvarchar(max) = ''
while 1=1
    begin
    declare @server sysname

    select  top 1 @server = name 
    from    @servers

    if @@rowcount = 0
        break

    if @query <> ''
        @query = @query + ' union all ' + char(13) + char(10)

    set @query = @query + 
        ' select * from ' + quotename(@server) + '.dbname.dbo.foo ' +
        char(13) + char(10)

    delete  @server
    where   name = @server
    end

print @query -- For debugging
exec (@query)



回答3:


I have done some work where I have had to join results from two linked servers. One of the linked servers is to a redbrick database and to make a long story short, I had to use openquery.

The approach that I used was to create temporary tables in ms sql. Then I populated them with the results from the openqueries to the linked servers and used normal tsql to put it all together.



来源:https://stackoverflow.com/questions/14945367/how-to-query-against-multiple-linked-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!