I have two tables and I have to transfer data from one to the other.
Table 1: employees
home_address string
Table 2 emp_address
address string emp_id int is_permanent bool
I need to migrate data from one to the other.
So I have only 2 conditions while inserting:
I cannot insert the address which has already been inserted into the emp_address for that employee.
The is_permanent flag is set to true if no address has been inserted for the employee (i.e. if no single entry is present for the employee set is as true else false)
I cannot seem to get my head around how to I do this.
Advertisement
Answer
Use not exists
:
insert into emp_address (address,emp_id,is_permanent) select ea.address, e.id, IIF(ea.number IS NOT NULL,0,1) from employees e left join dbo.emp_address ea on e.id=ea.emp_id where not exists ( select 0 from dbo.emp_address where e.id = emp_id and e.home_address = address ) and ea.address is not null