如果两个值都匹配,我需要比较两个表。 表的结构
Persons
ID | fname | lname | address | socialNumber | taxNumber | Match
Personals
ID | fname | lname | address | socialNumber | taxNumber
我有两个参数正在检查匹配,socialNumber和/或taxNumber。
此外,如果我想添加新参数以查找匹配(例如:地址),则可以使所有内容都尽可能动态。 这是我现在正在使用它的SQL代码,但我不知道如何根据我的需要扩展它。
UPDATE Persons SET Match = 1, ID = (SELECT MAX(ID) FROM Personals) WHERE taxNumber IN ( SELECT taxNumber FROM Personals GROUP BY taxNumber HAVING ( COUNT(taxNumber) > 1 ))
答案 0 :(得分:0)
我不认为您可以在单个查询中轻松完成此操作,而不是不使用游标,但您可以将操作分为两部分:
--update action
update a
set a.id = b.id, a.match =1
from _persons a inner join _personals b
on a.social = b.social or a.taxnumber = b.taxnumber
--delete / insert action
declare @RowCount as integer
select @RowCount = count(a.id) from _persons a
where ID not in (
select a.id
from _persons a inner join _personals b
on a.social = b.social or a.taxnumber = b.taxnumber
)
if @RowCount>0
begin
insert into _Personals (ID, fname, lname, address, social, taxnumber)
select ID, fname, lname, address, social, taxnumber from _persons a
where ID not in (
select a.id
from _persons a inner join _personals b
on a.social = b.social or a.taxnumber = b.taxnumber
)
delete _persons
where ID not in
(
select a.id
from _persons a inner join _personals b
on a.social = b.social or a.taxnumber = b.taxnumber
)
end