sql不存在查询

时间:2011-12-17 07:19:49

标签: sql sql-server tsql

我有以下sql查询

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 only

PEN - Pending       2

记录存在于tblRevisionStatus表中,为什么查询不返回其他记录。我在这里遗漏了什么?

3 个答案:

答案 0 :(得分:1)

如果您希望@Temp中的行列表不在tblRevisionStatus中,您可以使用 EXCEPT 语句轻松完成此操作

select RevisionStatus, DocType
from @Temp

except

select RevisionStatus, DocType
from tblRevisionStatus

答案 1 :(得分: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)

我仍然强调在所有表中使用主键

答案 2 :(得分: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
        )