如何对22个相似的数据库运行相同的参数?

时间:2019-05-31 15:52:44

标签: sql sql-server

我一直在从一个数据库中提取数据,该数据库将22个设施的数据存储在一起。现在已经重新设计了数据库,并且对于我们拥有的每个设施,都有22个单独的数据库(类似)。如何使用相同的代码并同时在所有这些数据库上运行它?例如,如何传递相同的参数并从所有22个数据库中提取数据?

1 个答案:

答案 0 :(得分:0)

您可以使用CURSOR来满足您的要求。在这里,我放置了一个示例动态插入脚本,您可以根据需要对其进行调整。一项手动任务是您必须使用脚本在临时表中插入22个数据库名称。该功能是一次性工作,您可以在需要时重新使用该脚本。

--The first step will be creating a Table variable 
--where you will INSERT all your database names 
--for a further loop as below- 

DECLARE @DbName VARCHAR(200)
DECLARE @DatabaseList TABLE (DbName VARCHAR(200))

INSERT INTO @DatabaseList (DbName) VALUES('db_name_1')
INSERT INTO @DatabaseList (DbName) VALUES('db_name_2')
--.......................
INSERT INTO @DatabaseList (DbName) VALUES('db_name_22')

--Now you can use CURSOR to generate the loop 
--and execute your required script as shown below

DECLARE db_cursor CURSOR FOR 
SELECT DbName FROM @DatabaseList

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @DbName  

WHILE @@FETCH_STATUS = 0  
BEGIN  

    --HERE You need to write your script That you
    --Execute for all your database. I have added
    --a sample script for your reference only

    -- You can see the Database Name inserted in the Script Dynamically from the Loop. 
    --The script could be INSERT/Update/DELETE As per requirement

    EXEC 
    (
        'INSERT INTO '+@DbName+'.dbo.<Your_table_Name_Here> 
        SELECT * FROM  master.dbo.<Your_table_Name_Here> '
    )

    --END OF Dynamic Part

    FETCH NEXT FROM db_cursor INTO @DbName 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor