如何通过不使用多个插入来编写单个查询,其中所有客户将具有具有相同地址的另一个地址3?

时间:2017-03-20 15:41:01

标签: sql-server

我在SQL SERVER中有一个像下面这样的表客户,

CUSTOMER(CUSTOMERID,ADDRESSID,ADDRESSTYPEID)
values(1,1001,2);(2,1002,2);(3,1003,2);(4,1004,2)

如何通过不使用多个插入来编写单个查询,其中所有客户将拥有具有相同地址的另一个地址3?

1 个答案:

答案 0 :(得分:1)

insert into customer_address (customerid, addressid, addresstypeid)
select customerid, addressid, 3
from customer_address
where addresstypeid = 2 /* where might not be needed */

仅为尚未拥有addresstypeid 3的客户插入

insert into customer_address (customerid, addressid, addresstypeid)
select customerid, addressid, 3
from customer_address c
where addresstypeid = 2
  and not exists (
    select 1
    from customer_address i
    where i.customerid = c.customerid 
      and i.addresstypeid = 3
      )