如果记录存在于子查询中,我正尝试将列值更新为“yes”,如果不存在则更新为“no”。我创建的代码表和临时表如下所示。
if object_id('tempdb..#t1') is not null drop table #t1
CREATE TABLE #t1 (id nvarchar(max), astate varchar(16), code varchar(16), qual_code_flag varchar(8))
INSERT into #t1 VALUES
(100.1, 'CA', '0123', null),
(100.2, 'CA', '0124', null),
(100.3, 'PA', '0256', null),
(200.1, 'MA', '0452', null),
(300.1, 'MA', '0578', null),
(400.2, 'CA', '1111', null),
(500.1, 'CO', '1111', null);
if object_id('tempdb..#t3') is not null drop table #t3
CREATE TABLE #t3 (qual_code varchar(16), qual_state varchar(8))
INSERT into #t3 VALUES
('0123', ''),
('0124', ''),
('0256', ''),
('0452', ''),
('0578', ''),
('1111', 'CO');
update t1
set qual_code_flag = case when t1.* in (
select t1.*
from #t3 t3
inner join #t1 t1
on t1.code = t3.qual_code
and (t3.qual_state = t1.astate or t3.qual_state = '')
) then 'yes' else 'no' end
from #t1 t1
select * from #t1
我希望这段代码能够正常工作,但是它抛出了一个错误,因为我试图在t1.*(子查询),这是不正确的语法。我知道如果我只是说,例如,当t1.code在(子查询),但我需要的是代码和状态的精确组合,以在子查询中。如果您运行子查询中的内容,你会看到#t1中的7条记录中有6条被返回。这些都是我想把标志更新为'yes'的记录,而在子查询中不存在的记录将有一个'no'的标志值。我认为这应该是一个简单的查询,但我还没有得到正确的结果。
2条答案
按热度按时间1szpjjfi1#
无需在子查询中重新打开目标表:相反,您可以使用
exists
和一个相关子查询:vmdwslir2#
你能离开吗?