Executing SQL query on multiple databases

前端 未结 7 1572
无人共我
无人共我 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条回答
  •  一整个雨季
    2021-01-02 19:40

    this is the normal way of doing this :

    suppose you want to do a select on database DBOther than it would be :

    select * from DBOther..TableName
    

    Also check if the table or view is on the dbo schema, if not you should add the schema also : Please notice I use only one dot now after the database name

    select * from DBOther.dbo.ViewName
    

    If any of the databases is on another server on another machine, than make sure the Database is in the Linked Server.
    Then you can access the table or view on that database via:

    SELECT * FROM [AnotherServerName].[DB].[dbo].[Table]
    

    Here is another way that does not requires typing the database name :

    use DB1
    go
    
    select * from table1
    go
    
    use DB2
    go
    
    select * from table1
    go
    

    Note that this will only work if the tables and fields are exact the same on each database

提交回复
热议问题