In the below syntax with the When Matched
is it possible to only update if the value in the update table differs from the value in the employee table? Something similar to my below DDL - but of course this throws an error and does not work.
What should I update in my syntax to only update rows that are different? My desired update would be to not iterate each and every row that matches, but only update emp44 & emp55
since the address is different.
The error presented is
Msg 156, Level 15, State 1, Line 24
Incorrect syntax near the keyword 'WHERE'.
Syntax
DECLARE @Emp Table (empid varchar(10), empaddress varchar(100))
Insert Into @Emp Values
('emp11', '111 No Blue'),
('emp22', '222 No Blue'),
('emp33', '333 No Blue'),
('emp44', '444 No Blue'),
('emp55', '555 No Blue');
Declare @EmpUpdates TABLE (empid varchar(10), empaddress varchar(100))
Insert Into @EmpUpdates Values
('emp11', '111 No Blue'),
('emp22', '222 No Blue'),
('emp33', '333 No Blue'),
('emp44', '999 No Blue'),
('emp55', '888 No Blue'),
('emp66', '4141 No Blue');
MERGE @Emp emp
Using @EmpUpdates eup
ON emp.empid = eup.empid
WHEN MATCHED THEN
UPDATE
SET emp.empaddress = eup.empaddress
WHERE emp.empaddress <> eup.empaddress
WHEN NOT MATCHED BY TARGET THEN
INSERT (empid, empaddress)
VALUES(eup.empid, eup.empaddress)