2011-12-17 86 views
0

我下面的SQL查詢SQL NOT EXISTS查詢

declare @temp table(RevisionStatus varchar(100),DocTypeID varchar(50)) 
insert into @temp(RevisionStatus,DocTypeID) 
select distinct md.RevisionStatus,dt.DocumentTypeID 
from MissingDesignData md inner join tblDocumentType dt on md.[Doc Type]=dt.DocumentType inner join tblRevisionStatus rv on md.RevisionStatus=md.RevisionStatus 

select distinct tm.RevisionStatus,tm.DocTypeID as 'DocType' 
from @temp tm 
rv.RevisionStatus=tm.RevisionStatus and rv.DocType=tm.DocTypeID 
where not exists (select distinct rss.RevisionStatus,rss.DocType from tblRevisionStatus rss) 

我需要返回的記錄,其中在tblRevisionStatus表不存在,但在@temp存在table.currently其返回空數據集

當我選擇@temp數據是如下

RevisionStatus DocType 
PEN - Pending 14 
PEN - Pending 16 
PEN - Pending 2 
PEN - Pending 3 
PEN - Pending 30 
PEN - Pending 34 
PEN - Pending 5 
PEN - Pending 55 

tblRevisionStatus數據集回報

RevisionStatus    DocType 

IFC - Issued For Construction  4 
RFD - Revised As Denoted    4 
IFU - Issued For Use   4 
AB - As Built    NULL 
C1 - Proceed, No Exception Taken   2 
PEN - Pending    1 
PEN - Pending    2 
HLD - HOLD (Implementation Study ONLY) 1 

當我運行上面給出的SQL查詢返回nothing.but只有

PEN - Pending  2 

在tblRevisionStatus表中存在的記錄,爲什麼查詢不返回其他records.am我失去了一些東西?

回答

0

實際的方法是使用主鍵這種類型的需求,但你可以試試下面的代碼在所有表

使用主鍵傳輸數據到臨時表

SELECT RevisionStatus,DocTypeID as 'DocType' 
from @temp where RevisionStatus not in(select distinct RevisionStatus From tblRevisionStatus) and DocTypeID not in (select distinct DocTypeID From tblRevisionStatus) 

我還是應激後選擇結果

+0

ohh.i修正,但仍處於最後的結果相同result.no數據集 – chamara 2011-12-17 07:34:57

1

如果你想那是@Temp不在tblRevisionStatus行的列表,你可以很容易地做到這一點使用EXCEPT聲明

select RevisionStatus, DocType 
from @Temp 

except 

select RevisionStatus, DocType 
from tblRevisionStatus 
0

我建議你不要使用IN和DISTICTS。這些在大多數情況下對性能不利。所以我的建議是這樣的:

SELECT 
    tbl.RevisionStatus, 
    tbl.DocTypeID as 'DocType' 
FROM 
    @temp AS tbl 
WHERE NOT EXISTS 
    (
     SELECT 
      NULL 
     FROM 
      tblRevisionStatus 
     WHERE 
      tblRevisionStatus.RevisionStatus=tbl.RevisionStatus 
    ) 
    AND NOT EXISTS 
     (
      SELECT 
       NULL 
      FROM 
       tblRevisionStatus 
      WHERE 
       tblRevisionStatus.DocTypeID=tbl.DocTypeID 
     )