如果我上传了一个表,那么我要如何将这个表和另一个表对比并直接更新呢?
SQL Merge
SQL Shack Merge 答案是使用SQL Merge函数。
SQL 核对并更新
我们先用参考网站的举例:
代码语言:javascript复制USE SqlShackMergeDemo
GO
MERGE TargetProducts AS Target
USING SourceProducts AS Source
ON Source.ProductID = Target.ProductID
-- For Inserts
WHEN NOT MATCHED BY Target THEN
INSERT (ProductID,ProductName, Price)
VALUES (Source.ProductID,Source.ProductName, Source.Price)
-- For Updates
WHEN MATCHED THEN UPDATE SET
Target.ProductName = Source.ProductName,
Target.Price = Source.Price;
例如我们需要更新PeopleEmailList这个表,这表里有100个人,但是我上传的临时表里只有15个人(需要修改)。 且我们Source的表是需要先和别的表合并展示才可以的,那么我们需要先Join查询并加上括号:
代码语言:javascript复制
MERGE PeopleEmailList
USING(
Select bi.PeopleID, bi.Surname, bi.ForeName,bi.PreferredForeName,bi.PreferredSurname
,import.EmployeeID
,import.EmailAddress
From BasicInformation bi
Inner Join ztemp_20220901 as import on bi.PeopleID = import.EmployeeID
) AS Base on Base.PeopleID = PeopleEmailList.PeopleID
When MATCHED THEN
Update
Set PeopleEmailList.EmailID = Base.EmailAddress;