简体   繁体   English

T-SQL使用链接服务器查询结果填充本地表

[英]T-SQL use linked server query result to populate a local table

Hi I am trying to get smart ideas how to accomplish this. 嗨,我正在尝试获得一些精妙的想法,以实现这一目标。 I have a table T1 with a column named 'Servers' containing a whole list of linked server names. 我有一个表T1,其中的列名为“服务器”,其中包含链接服务器名称的整个列表。 And I want to query some tables on each of these linked servers and use the result to populate the other columns, named DB_Nmaes for example, of this table. 我想查询每个链接服务器上的一些表,并使用结果填充该表的其他列,例如,名为DB_Nmaes的列。

The ideal resulted table after would be like this 理想的结果表如下所示

T1 T1

Servers  DB_Names    Datafile_Size, …. 
S1 D1 2M S1 D2 3M S1 D3 5M S2 D1 3M S2 D2 6M . . .

One way I could think of is to loop through the whole table T1 and construct a dynamic SQL in each loop to query the corresponding linked server and insert to the other fields DB_Names and Datafile_size. 我可以想到的一种方法是遍历整个表T1,并在每个循环中构造一个动态SQL,以查询相应的链接服务器并将其插入其他字段DB_Names和Datafile_size。 But I am trying to avoid doing this because I have many linked servers rows in that column. 但是我试图避免这样做,因为在该列中有很多链接服务器行。 Is there any way we could accomplish this by using set based operations? 有什么方法可以通过使用基于集合的操作来完成此操作?

Thanks. 谢谢。

Since you want all databases on the remote servers I would consider changing to a 2 table approach. 由于您希望所有数据库都位于远程服务器上,因此我将考虑更改为2表方法。 Your first table will be a table containing all of the linked servers you wish to query. 您的第一个表将是一个包含您要查询的所有链接服务器的表。 You'd then need to loop through a cursor that would formulate dynamic SQL statements in order to make the call across the linked servers. 然后,您需要遍历游标,该游标将制定动态SQL语句,以便跨链接的服务器进行调用。

I would also suggest to store the result in separate table. 我也建议将结果存储在单独的表中。 Then you can approach it in this way: 然后,您可以通过以下方式进行处理:

CREATE TABLE ServerDbs (LinkedServer VARCHAR(100), DbName VARCHAR(100))

DECLARE @q VARCHAR(MAX)
SET @q = 
    (SELECT 'INSERT INTO ServerDbs SELECT ''' + T.Server + ''', name FROM ' + T.Server + '.master.sys.databases'
    FROM T
    FOR XML PATH(''))

EXEC (@q)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM