mercredi 27 mars 2019

Insert New Records Into Table Using If/Else Statement

I have two SQL Server tables where I need to add records from one table to the next. If the unique identifier already exists in the target table, then update the record to the data coming from source table - If the unique identifier doesn't exist, then insert the entire new record into the target table.

I seem to have gotten the initial part to work where I update the records in target table but the the part where I would INSERT new records does not seem to be working.

if exists (select 1
           from SCM_Top_Up_Operational O
           join SCM_Top_Up_Rolling R ON O.String = R.string)
begin
update O
set    O.Date_Added = R.Date_Added,
      O.Real_Exfact = R.Real_Exfact,
      O.Excess_Top_Up = R.Excess_Top_Up 

from  SCM_Top_Up_Operational O 
join  SCM_Top_Up_Rolling R on O.String = R.String

where O.String = R.string 
and   R.date_added > O.date_added
end

else 

begin
   insert into SCM_Top_Up_Operational (String,Date_Added,Real_Exfact,Article_ID,Excess_Top_Up,Plant)
   select String,Date_Added,Real_Exfact,Article_ID,Excess_Top_Up,Plant
   from SCM_Top_Up_Rolling
end

Aucun commentaire:

Enregistrer un commentaire