query with join across multiple databases-syntax error

后端 未结 3 1780
醉酒成梦
醉酒成梦 2021-01-25 19:45

I have 2 databases namely db1,db2. I need a query that fetch the data from these dbs(db1,db2) which have inturn 2 tables(concessions,invoicing) each.

In db1.concessions

相关标签:
3条回答
  • 2021-01-25 20:15
    select * from(
    SELECT a.concession as db1_CON_NUMBER FROM BABMwork6_5_3108.dbo.concessions as a  
            WHERE (a.manuell_archive_delete! = 'Delete' OR  a.manuell_archive_delete IS NULL) 
    UNION SELECT b.[Concession Number] as db1_CON_NUMBER  FROM BABMwork6_5_3108.dbo.invoicing as b) as tbl1 
    INNER JOIN 
    (SELECT c.concession as db2_CON_NUMBER FROM BABMwork6_6_2909.dbo.concessions as c  
            WHERE (c.manuell_archive_delete! = 'Delete' OR  c.manuell_archive_delete IS NULL) 
    UNION SELECT d.[Concession Number] as db2_CON_NUMBER  FROM BABMwork6_6_2909.dbo.invoicing as d ) as tbl2
    ON tbl1.[db1_CON_NUMBER] = tbl2.[db2_CON_NUMBER]
    
    0 讨论(0)
  • 2021-01-25 20:27

    If the databases are on the same SQL Server instance you can use 3 part naming:

    database_name.schema_name.object_name
    

    Using Identifiers As Object Names

    If the databases are not on the same instance, create a linked server: Linked Servers

    Creating Linked Servers (SQL Server Database Engine)

    A linked server allows for access to distributed, heterogeneous queries against OLE DB data sources. After a linked server is created, distributed queries can be run against this server, and queries can join tables from more than one data source. If the linked server is defined as an instance of SQL Server, remote stored procedures can be executed.

    0 讨论(0)
  • 2021-01-25 20:40

    You can reference other databases directly if the user has permissions.

    <database>.<user>.<tablename>
    

    Is the full "path" to the database table.

    Often you use

    db1.dbo.tbl1 join db2.dbo.tbl2
    

    where dbo is default for database owner, any table not owned by a specific user is owned by dbo by default.

    UPDATE

    To get the query to validate you can expand it to this

    SELECT * FROM 
    (SELECT a.concession as db1_CON_NUMBER FROM db1.dbo.concessions as a  
    UNION 
    SELECT b.[Concession Number] as db1_CON_NUMBER FROM db1.dbo.invoicing as b ) c
    
    INNER JOIN 
    
    (SELECT c.concession as db2_CON_NUMBER FROM db2.dbo.concessions as a 
    UNION 
    SELECT b.[Concession Number] as db2_CON_NUMBER FROM db2.dbo.invoicing as b ) d
    
    ON db1_CON_NUMBER = db2_CON_NUMBER 
    

    But I have not had time to check if this would return the right data but you can test.

    0 讨论(0)
提交回复
热议问题