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 新手!
有很多选择。
归档时间: |
|
查看次数: |
6819 次 |
最近记录: |