SQL statement to select from 2 different tables, from two different databases (same server)

后端 未结 3 1387
难免孤独
难免孤独 2021-01-21 00:38

How do I select from multiple tables in different databases on the same server?

Also, Is there a way to have an identifying marker so I could see where the results came

相关标签:
3条回答
  • 2021-01-21 00:51

    You could use a UNION ALL and add in the database name like:

    SELECT [columns_list], 'db1.schema.table1.name' AS [fromTbl]
    FROM db1.schema.table1
    WHERE db1.schema.table1.name LIKE '%j%' 
    UNION ALL
    SELECT [columns_list], 'db2.schema.table2.name' AS [fromTbl]
    FROM db2.schema.table2
    WHERE db2.schema.table2.name LIKE '%j%'
    

    This will only work if the columns in the tables have the same column types (as your example suggests) else UNION will not work.

    0 讨论(0)
  • 2021-01-21 00:53

    Doing a union seems like your best bet here. A union will combine the results of two queries.

    select name, 'table1' as fromTbl
    from db1.schema.table1
    where name like '%j%'
    
    union --or union all depending on what you want
    
    select name, 'table2' as fromTbl
    from db2.schema.table2
    where name like '%j%'
    
    0 讨论(0)
  • 2021-01-21 00:58

    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)
提交回复
热议问题