插入子查询并选择

时间:2015-10-28 13:33:35

标签: sql select insert subquery

我想使用select语句将行插入表中以查询特定数据,但使用来自不同表的数据作为插入的一部分。 〔实施例: 表A:正在查询和复制数据的客户端 表B:正在插入数据的MailOptOut

我想在MailOptOut表中插入两个值,一个硬编码字段' Summer Promotion'然后是来自客户表的acct#(client.acct_no)

以下是我的代码:

INSERT INTO PL00.DBO.mailcoptout (MC_NAME, ACCT_NO)
VALUES 
('Summer Service Promo',  client.acct_no),
('Referral Rewards Doubled', client.acct_no),
('Holiday Decorating 1',  client.acct_no),
('Holiday Decorating 2', client.acct_no)
select client.acct_no, mailcoptout.* from plshared.dbo.client  left join PL00.DBO.mailcoptout on mailcoptout.ACCT_NO = client.ACCT_NO
where client.U_SOLICIT = 'y'
and client.acct_no = '131335'
and client.INACTIVE <> 'y'
and mailcoptout.MC_NAME is null

1 个答案:

答案 0 :(得分:1)

这是你想要做的吗?

INSERT INTO PL00.DBO.mailcoptout (MC_NAME, ACCT_NO)
    select x.mc_name, client.acct_no
    from plshared.dbo.client c left join
         PL00.DBO.mailcoptout mc
         on mailcoptout.ACCT_NO = client.ACCT_NO cross join
         (select 'Summer Service Promo' as MC_NAME union all,
          select 'Referral Rewards Doubled' as MC_NAME union all
          select 'Holiday Decorating 1' as MC_NAME union all
          select 'Holiday Decorating 2' as MC_NAME
         ) x
    where c.U_SOLICIT = 'y' and
          c.acct_no = '131335' and
          c.INACTIVE <> 'y' and
          mc.MC_NAME is null;