【问题标题】:insert with subquery and select插入子查询并选择
【发布时间】:2016-01-28 07:26:04
【问题描述】:

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

【问题讨论】:

  • 请包括错误(如果有的话)并解释什么不工作。
  • 它抛出了什么错误?
  • 您的insert 语句插入了两列,谁知道您尝试了多少列。请编辑您的问题并提供示例数据。另外,用你正在使用的数据库标记问题。
  • 使用sql server management studio

标签: sql select insert subquery


【解决方案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;

【讨论】:

  • 我试过这个并得到这个错误:Msg 4104, Level 16, State 1, Line 5 无法绑定多部分标识符“mailcoptout.ACCT_NO”。消息 4104,级别 16,状态 1,行 5 无法绑定多部分标识符“client.ACCT_NO”。消息 4104,级别 16,状态 1,行 2 无法绑定多部分标识符“client.acct_no”。
  • 调整一些错误:INSERT INTO PL00.DBO.mailcoptout (MC_NAME, ACCT_NO) select x.mc_name, c.acct_no from plshared.dbo.client c left join PL00.DBO.mailcoptout mc on mc .ACCT_NO = c.ACCT_NO 交叉加入(选择“Summer Service Promo”作为 MC_NAME union all 选择“Referral Rewards Doubled”作为 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.INACTIVE 'y' and mc.MC_NAME is null;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 2016-08-26
  • 2014-09-01
相关资源
最近更新 更多