In SQL Server 2016, I have 2 tables (Del_Test_Main and Del_Test_Stg) Later will always get the latest list of Active Id's based on which I want to update the main table.
But there are multiple scenarios:
If the main table has an Id that does not exist in the Stg table, then Update IsDelete column of the main table to 1 and update Rootpid only for those rows.
If the main table has an Id that also exists in Stg table, but IsDelete column value is 1 in the Main table then Update IsDelete column to 0 and update Rootpid only for those rows.
Input Query:
Create table Del_Test_Main ( uniqueId bigint identity not null, Id int, Name varchar(50), IsDelete tinyint default 0, RootPid varchar(50) ) insert into Del_Test_Main (Id,Name,IsDelete,RootPid) values (1,'Vj',0,'20190101') , (2,'john',0,'20190101'), (3,'lance',1,'20190101' ), (4,'kate',1,'20190101' ) Create table Del_Test_Stg ( Id int ) insert into Del_Test_Stg (Id) values (1) ,(3) select * from Del_Test_Main select Id as ActiveIds from Del_Test_Stg Using below update queries I can achieve expected results. But how can I get it done in a single update query for both Scenarios? Also, the count of Id's will be in thousands and millions so also need to consider about the query from a performance perspective.
-- S1 SELECT main.Id AS "List_Of_Ids_to_Update_in_main_AS_1" --UPDATE main --SET IsDelete = 1, RootPid = '20190202' FROM ..Del_Test_Main main LEFT JOIN .. Del_Test_Stg del ON main.Id=del.Id WHERE del.Id IS NULL AND main.IsDelete = 0 -- S2 SELECT main.Id AS "List_Of_Ids_to_Update_in_main_AS_0" --UPDATE main --SET IsDelete = 0, RootPid = '20190202' FROM ..Del_Test_Main main INNER JOIN ..Del_Test_Stg del ON main.Id=del.Id WHERE main.IsDelete = 1 