Selecting data from two different servers in SQL Server

后端 未结 15 1691

How can I select data in the same query from two different databases that are on two different servers in SQL Server?

相关标签:
15条回答
  • 2020-11-22 07:54

    Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

    1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
    2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
    3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
    4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
    5. OPENQUERY: Doesn't support variables
    6. All are T-SQL solutions. Relatively easy to implement and set up
    7. All are dependent on connection between source and destionation which might affect performance and scalability
    0 讨论(0)
  • 2020-11-22 07:57
    sp_addlinkedserver('servername')
    

    so its should go like this -

    select * from table1
    unionall
    select * from [server1].[database].[dbo].[table1]
    
    0 讨论(0)
  • 2020-11-22 07:59
     select * 
     from [ServerName(IP)].[DatabaseName].[dbo].[TableName]
    
    0 讨论(0)
  • 2020-11-22 08:00

    try this:

    SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
    UNION
    SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
    
    0 讨论(0)
  • 2020-11-22 08:00

    Simplified solution for adding linked servers

    First server

    EXEC sp_addlinkedserver @server='ip,port\instancename'
    

    Second Login

    EXEC sp_addlinkedsrvlogin 'ip,port\instancename', 'false', NULL, 'remote_db_loginname', 'remote_db_pass'
    

    Execute queries from linked to local db

    INSERT INTO Tbl (Col1, Col2, Col3)
    SELECT Col1, Col2, Col3
    FROM [ip,port\instancename].[linkedDBName].[linkedTblSchema].[linkedTblName]
    
    0 讨论(0)
  • 2020-11-22 08:01

    Server Objects---> linked server ---> new linked server

    In linked server write server name or IP address for other server and choose SQL Server In Security select (be made using this security context ) Write login and password for other server

    Now connected then use

    Select * from [server name or ip addresses ].databasename.dbo.tblname
    
    0 讨论(0)
提交回复
热议问题