Executing SQL query on multiple databases

前端 未结 7 1612
无人共我
无人共我 2021-01-02 19:25

I know my post has a very similar title to other ones in this forum, but I really couldn\'t find the answer I need.

Here is my problem, I have a SQL Server running o

7条回答
  •  Happy的楠姐
    2021-01-02 19:52

    Depending on the requirement, you can do this:

    
    declare @dbName nvarchar(100)
    declare @script nvarchar(max)
    declare @dbIndex bigint = 0
    declare @dbCount bigint = (
        select count(*) from
            sys.databases
    
        )
    declare crs_databases cursor for
    (
        select
            [name]
        from
            sys.databases   
    )
    open crs_databases
    fetch next from crs_databases into @dbName
    while @@FETCH_STATUS = 0
    begin
        set @dbIndex = @dbIndex+1
        set @script = concat(@script,
            ' select Id from ['+@dbName+']..YourTableName ',        
            case 
                when @dbIndex = @dbCount then ''
                else 'union'
            end)
        fetch next from crs_databases into @dbName
    end
    
    select @script
    close crs_databases
    deallocate crs_databases
    
    

    Please note that the double dotted notation assumes that the schema is dbo. Otherwise, you need to explicitly write down the schema.

    select Id from ['+@dbName+'].schema.YourTableName
    

    When you need to execute stored procedures on each server, the @script variable will have another content.

提交回复
热议问题