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

后端 未结 3 1458
难免孤独
难免孤独 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.

提交回复
热议问题