2016-05-30 58 views
-1

我下面的查詢導致錯誤:附近有語法錯誤「加入」

Incorrect syntax near the keyword 'join'.

Select top 1 
    a.mkey, emp_received, a.mkey, 
    c.type_desc DOC_TYPE, a.doc_no INWARD_NO, 
    c.type_desc dept_received, c.type_desc EMP_RECEIVED, 
    convert(varchar, a.doc_date, 103) date, 
    a.to_user, a.No_of_pages, Ref_No, c.type_desc, 
    e.emp_name NAME, 
    ISNULL(e.Email_Id_Official, '[email protected]') EMAILID 
from 
    inward_doc_tracking_hdr a 
left join 
    type_mst_a c on a.doc_type = c.master_mkey 
       and 
left join 
    type_mst_a c on a.dept_received = c.master_mkey 
left join 
    emp_mst e on a.emp_received = e.mkey 
where 
    a.emp_received is not null 
    and a.mkey = (select mkey 
        from inward_doc_tracking_hdr aa 
        where doc_no='IW/16/97') 

我不知道爲什麼它是導致該錯誤

按照戈登的回答,我爲emp_received添加了一個左連接,但它不起作用

Select top 1 a.mkey, 
      cd.type_desc as DOC_TYPE, a.doc_no as INWARD_NO, 
      cr.type_desc as DEPT_RECEIVED, qr.type_desc 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, '[email protected]') EMAILID 
    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.emp_received = qr.master_mkey left join 
     type_mst_a st 
     on a.dept_received = cr.master_mkey left join 
     emp_mst e 
     on a.emp_received = e.mkey 
    where a.emp_received is not null and 
      a.mkey = (select mkey 
        from inward_doc_tracking_hdr aa 
        where doc_no = 'IW/16/97' 
        ); 
+3

'和left join':這不是SQL構造。 –

+0

通過刪除'和'仍然出現錯誤 – BNN

+0

這是因爲'left.emp_received = qr.master_mkey上的type_mst_a cr'。你指的是'qr',你可能是指'cr'。 (請參閱Gordon的代碼。) – HoneyBadger

回答

3

我想你想查詢更是這樣的:

Select top 1 a.mkey,emp_received , 
     a.mkey, cd.type_desc as DOC_TYPE, a.doc_no as INWARD_NO, 
     cr.type_desc as dept_received, cr.type_desc 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, '[email protected]') as EMAILID 
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 left join 
    emp_mst e 
    on a.emp_received = e.mkey 
where a.emp_received is not null and 
     a.mkey = (select mkey 
       from inward_doc_tracking_hdr aa 
       where doc_no = 'IW/16/97' 
       ); 

注:

  • 眼前的問題是and left joinand會導致語法錯誤。
  • 你有兩個具有相同別名的表。這是不允許的。
  • 您需要注意哪些列來自哪些表;我做了一個很好的猜測。
  • 無論何時在SQL Server中使用varchar(),都要包含一個長度。默認長度因上下文而異,如果您懶惰,您可能會在某個時候遭受難以調試的錯誤。
  • 定義列別名時使用as
+0

我想再爲'emp_recevied'添加一個desc,所以我可以在'on a.doc_type = cd.master_mkey左加入之前添加' type_mst_a cr' – BNN

+0

請參閱我的問題以獲取更多更新,我嘗試了一個更多參數,但它是不工作 – BNN

+0

@NK。 。 。我不確定新查詢應該做什麼。你應該問一個新的問題。 –