查询多个实例的脚本

Ala*_*ted 4 sql-server t-sql

SQL Server - 在多个实例上的多个数据库上运行相同查询的最佳方法是什么?例如,我们有许多应用程序数据库,具有相同的架构,需要聚合信息。

我目前使用的脚本依赖于已设置的链接服务器和一个用于标识要循环的实例和数据库的表。

        /* 声明一些游标变量和动态sql字符串变量 */
    声明 @currentDB nvarchar(64)
    声明 @connectionstring nvarchar(256)
    声明 @sqlstring nvarchar(max)

CREATE TABLE #TEMP1 ( currentDB varchar(32) ,field1 varchar(128) ,field2 smallint ,field3 datetime ) /* Build and open the cursor */ DECLARE connectioncursor CURSOR FAST_FORWARD FOR SELECT currentDB, connectionstring FROM [admin].dbo.DatabaseList WHERE dbtype = 'PROD' OPEN connectioncursor FETCH NEXT FROM connectioncursor INTO @currentDB, @connectionstring /* Start the loop through db list */ WHILE @@FETCH_STATUS = 0 BEGIN /* Build and set the sql string */ SET @sqlstring = ' select ''' + @currentDB + ''' ,field1, field2, field3 from ' + @connectionstring + '.dbo.table1 ' /* Insert the results from the iteration and fetch the next db */ INSERT INTO #TEMP1 exec sp_executesql @sqlstring FETCH NEXT FROM connectioncursor INTO @currentDB, @connectionstring END /* Kill the cursor */ CLOSE connectioncursor DEALLOCATE connectioncursor

Run Code Online (Sandbox Code Playgroud)

select * from #TEMP1 -- 一些输出

温柔点,我是 TSQL 新手!

mrd*_*nny 5

有很多选择。

  • 游标和 dSQL 非常适合这样的事情,因为没有其他选择。您正在控制代码,因此像这样推出它应该不是问题。您依赖于正确设置的链接服务器,但在我看来这是可以接受的风险。 (2认同)