我正在使用SQL Server:我需要根据逐个检查两个列值来更新临时表中的列(电话号码)。这是我当前的代码版本:基本上它的作用是,它根据匹配连接条件的位置设置临时表中列的值。
update r
set t.phone_number = tb.phone_number
from #temptable t
inner join phone_number_records tb
on t.id = tb.id
and 1 = tb.is_this_valid
现在我需要检查phone_number_records表中的另一个列值(ready_to_accept_new),并根据ready_to_accept_new值更新临时表中的phone_number字段。如果ready_to_accept_new等于“1”并且temptable的“id”与phone_number_records的“id”匹配,则需要在匹配记录phone_number(在phone_number_records表中)的temptable中设置phone_number值。如果此条件上没有匹配的记录,我们需要像以前一样更新临时表记录(来自匹配的is_this_valid列值“1”记录)。
有人可以让我知道如何解决这个问题吗?提前谢谢!
答案 0 :(得分:0)
最快的方法是两次加入你的牌桌。 对每个ready_to_accept_new值连接使用左连接,然后使用case语句查看是否存在。 IE:
update r
set t.phone_number =
CASE
WHEN tb_1.id IS NOT NULL THEN tb_1.phone_number
ELSE tb.phone_number
END
from #temptable t
inner join phone_number_records tb
on t.id = tb.id
and 1 = tb.is_this_valid
left join phone_number_records tb_1
on t.id = tb.id
and 1 = tb.per ready_to_accept_new value
格式化道歉!
答案 1 :(得分:0)
除了John提供的答案之外,还可以使用IF..ELSE块
来完成if exists(select * from #temptable t
inner join phone_number_records tb
on t.id = tb.id
and 1 = tb.ready_to_accept_new )
update r
set t.phone_number = tb.phone_number
from #temptable t
inner join phone_number_records tb
on t.id = tb.id
and 1 = tb.ready_to_accept_new
else
update r
set t.phone_number = tb.phone_number
from #temptable t
inner join phone_number_records tb
on t.id = tb.id
and 1 = tb.is_this_valid