我有一个有帐号和卡号的数据库。我将这些匹配到一个文件,以将任何卡号更新为帐号,这样我只使用帐号。
我创建了一个将表链接到帐户/卡数据库的视图,以返回table ID和相关的帐号,现在我需要更新那些ID与account number匹配的记录。
这是Sales_Import表,其中的帐号字段需要更新:
LeadID |
AccountNumber |
147 |
5807811235 |
150 |
5807811326 |
185 |
7006100100007267039 |
这是RetrieveAccountNumber表,我需要从这里更新:
LeadID |
AccountNumber |
147 |
7006100100007266957 |
150 |
7006100100007267039 |
我尝试了下面的方法,但到目前为止运气都不佳:
UPDATE [Sales_Lead].[dbo].[Sales_Import]
SET [AccountNumber] = (SELECT RetrieveAccountNumber.AccountNumber
FROM RetrieveAccountNumber
WHERE [Sales_Lead].[dbo].[Sales_Import]. LeadID =
RetrieveAccountNumber.LeadID)
它将卡号更新为帐号,但是帐号被NULL替换
总结其他答案,关于如何仅在“匹配存在”时使用来自另一个表的数据更新目标表,有4种变体
查询和子查询:
update si
set si.AccountNumber = (
select ran.AccountNumber
from RetrieveAccountNumber ran
where si.LeadID = ran.LeadID
)
from Sales_Import si
where exists (select * from RetrieveAccountNumber ran where ran.LeadID = si.LeadID)
内连接:
update si
set si.AccountNumber = ran.AccountNumber
from Sales_Import si inner join RetrieveAccountNumber ran on si.LeadID = ran.LeadID
交叉连接:
update si
set si.AccountNumber = ran.AccountNumber
from Sales_Import si, RetrieveAccountNumber ran
where si.LeadID = ran.LeadID
走:
merge into Sales_Import si
using RetrieveAccountNumber ran on si.LeadID = ran.LeadID
when matched then update set si.accountnumber = ran.accountnumber;
所有的变体都是更少的琐碎和可以理解的,我个人更喜欢“内部连接”选项。但其中任何一种都可以使用,开发者必须根据自己的需求选择“更好的选项”
从性能的角度来看,使用join的变体更可取:
在同一个表内更新:
DECLARE @TB1 TABLE
(
No Int
,Name NVarchar(50)
,linkNo int
)
DECLARE @TB2 TABLE
(
No Int
,Name NVarchar(50)
,linkNo int
)
INSERT INTO @TB1 VALUES(1,'changed person data', 0);
INSERT INTO @TB1 VALUES(2,'old linked data of person', 1);
INSERT INTO @TB2 SELECT * FROM @TB1 WHERE linkNo = 0
SELECT * FROM @TB1
SELECT * FROM @TB2
UPDATE @TB1
SET Name = T2.Name
FROM @TB1 T1
INNER JOIN @TB2 T2 ON T2.No = T1.linkNo
SELECT * FROM @TB1