从同一个表中获取一列加入但不同的数据库

时间:2016-07-04 07:41:42

标签: sql sql-server sql-server-2005

我有两个数据库。

一个。 DB_1 b。 DB_2

比方说,我目前正在使用DB_1进行以下查询

Select top 1 a.mkey,convert(varchar(255), a.ref_date,103) as REF_DATE,  cd.type_desc as DOC_TYPE,  a.doc_no as INWARD_NO, 
                       cr.type_desc as dept_received, e.emp_name as EMP_RECEIVED,    
                       convert(varchar(255), a.doc_date,103) as date,   
                       a.to_user, a.No_of_pages, Ref_No,    
                       e.emp_name as NAME,    
                       coalesce(e.Email_Id_Official, 'test@test.com') EMAILID, a.Party_Name                           
                from inward_doc_tracking_hdr a left join   
                     type_mst_a cd   
                     on a.doc_type = cd.master_mkey left join  
                   type_mst_a cr   
                     on a.dept_received = cr.master_mkey 
                     and cr.type_code='D1'  
                     left join  emp_mst e  
                     on a.emp_received = e.mkey   
                     where a.emp_received is not null and
                        a.mkey = 146

现在我想要的是。我想从另一个数据库(DB_2)加入同一个表怎么做?

更新

我的另一个数据库列名是Inward_ref_key,其表名是inward_doc_tracking_hdr

4 个答案:

答案 0 :(得分:1)

正如所讨论的那样。请参阅下面的答案。

SELECT TOP 1 a.mkey,
    CONVERT(VARCHAR(255), a.ref_date,103) AS REF_DATE, 
    cd.type_desc AS DOC_TYPE, 
    a.doc_no AS INWARD_NO, 
    cr.type_desc AS dept_received, 
    e.emp_name AS EMP_RECEIVED, 
    CONVERT(VARCHAR(255), a.doc_date,103) AS DATE, 
    a.to_user,
    a.No_of_pages,
    Ref_No, 
    e.emp_name AS NAME, 
    COALESCE(e.Email_Id_Official, 'test@test.com') EMAILID, 
    a.Party_Name, 
    doc_no = (SELECT TOP 1 doc_no FROM erp190516.dbo.inward_doc_tracking_hdr WHERE mkey = a.inward_ref_key)
    OLD_DOC_NO 
FROM inward_doc_tracking_hdr a 
LEFT JOIN type_mst_a cd 
    ON cd.master_mkey  = a.doc_type  
LEFT JOIN type_mst_a cr 
    ON cr.master_mkey = a.dept_received 
    AND cr.type_code='D1' 
LEFT JOIN emp_mst e 
    ON  e.mkey = a.emp_received
WHERE a.emp_received IS NOT NULL 
AND a.mkey = 146

答案 1 :(得分:0)

假设两个数据库都在同一台服务器上,您只需将另一个数据库指定为表标识符的一部分:

DB_2.dbo.inward_doc_tracking_hdr

如果您的表属于不同的架构(不是dbo),请指定该架构名称。

答案 2 :(得分:0)

为了从另一个数据库引用表,你可以这样:

DB_2.<schema>.<table_name>

如果他们有不同的排序规则,请小心

答案 3 :(得分:0)

SELECT local.name AS LocalLogins, linked.name AS LinkedLogins  
FROM master.sys.server_principals AS local  
LEFT JOIN [SRVR002\ACCTG].master.sys.server_principals AS linked  
ON local.name = linked.name ;  
GO  

此处[SRVR002 \ ACCTG]是DB的名称,如果您已经创建了DBlink,这应该可行