首页 > 解决方案 > 将数据从一个表迁移到另一个表

问题描述

我有两张表,我必须将数据从一张表传输到另一张表。

表 1:员工

home_address string

表 2 emp_address

address      string 
emp_id       int 
is_permanent bool

我需要将数据从一个迁移到另一个。

所以我在插入时只有两个条件:

  1. 我无法插入已插入该员工的emp_address的地址 。

  2. 如果没有为员工插入地址,则is_permanent标志设置为 true(即,如果员工集不存在单个条目,则为 true,否则为 false)

我似乎无法理解如何做到这一点。

标签: sqlsql-insert

解决方案


使用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

推荐阅读