当基于修订 ID 的临时 table 位置上仅存在值站点程序集时,如何进行状态更新?

How to make status update when only value site assembly exist on temp table location based on Revision Id?

我在处理 SQL Server 2012 查询时遇到一个问题:当临时 table #rev 上的至少一个装配站点记录与临时匹配时,我无法更新状态table #location 基于修订 ID 。

预期结果是:

Revision Id   Status    
------------------------
1900          Found
2000          Not Found
5000          Found

例如:修订 ID 1900 状态将为 Found,因为临时 table #rev 中的修订 ID 1900 等于临时 table 中的 LocRevisionId ] #location 和临时 table #rev 中的组装站点等于临时 table #location 中的 locAssemblySiteId 至少一次。

Revision Id 2000 状态将为 Not Found,因为 #rev 中的 Revision Id 2000 等于 #location 中的 LocRevisionId 并且 #rev 中的 Assembly Site 是在 #location 中至少有一次不等于 locAssemblySiteId

create table #rev
(
    RevisionId int,
    AssemblySiteId int,
    Status nvarchar(200)
)

insert into #rev (RevisionId, AssemblySiteId)
values (1900, 200), (2000, 300), (5000, 800)

create table #location
(
    locRevisionId int,
    locAssemblySiteId int
)

insert into #location (locRevisionId, locAssemblySiteId)
values (1900, 200), (1900, 150),
       (2000, 290), (2000, 310),
       (5000, 800), (5000, 820)

您可以使用 existscase 表达式:

update #rev
set status = case 
    when exists (
        select 1
        from #location l
        where 
            l.locRevisionId = #rev.RevisionId 
            and l.locAssemblySiteId = #rev.AssemblySiteId
    )
    then 'Found'
    else 'Not Found'
end;

如果每次修订的位置 table 中始终最多只有一行,那么 left join 也是一个可能的选项:

update r
set r.status = case when l.locRevisionId is null then 'Not Found' else 'Found' end
from #rev r
left join #location l 
    on l.locRevisionId = r.RevisionId 
    and l.locAssemblySiteId = r.AssemblySiteId
)