【问题标题】:Update query comparing two tables - Oracle更新比较两个表的查询 - Oracle
【发布时间】:2014-09-17 22:25:16
【问题描述】:

当 aif_hyp_acct_type 表中的 account_type 为“”、“R”、“L”、“Q”时,我正在尝试更改 tdataseg 表中金额字段的符号。 aif_hyp_acct_type 是主表。它有 loadid、account 和 account_type 字段。 tdataseg表有account、amount等很多字段。

我尝试了这个查询并得到 ORA-01427 错误。

单行子查询返回多行。


update tdataseg
set tdataseg.amount = 
    (select decode(sign(tdataseg.amount),-1,abs(tdataseg.amount),1,-abs(tdataseg.amount),0) 
     from tdataseg, aif_hyp_acct_type 
     where tdataseg.loadid = aif_hyp_acct_type.loadid 
           and tdataseg.account = aif_hyp_acct_type.account 
           and aif_hyp_acct_type.account_type in (' ','R','L','Q'))

【问题讨论】:

  • 该错误表明您的 SELECT 子查询返回超过 1 行。自行运行并亲自查看。

标签: sql oracle oracle11g sql-update


【解决方案1】:

大概问题在于您认为您有一个相关的子查询,但您没有。外部表在内部查询中提到。您需要删除该引用:

update tdataseg
    set tdataseg.amount = (select decode(sign(tdataseg.amount), -1, abs(tdataseg.amount),
                                         1,-abs(tdataseg.amount), 0) 
                           from aif_hyp_acct_type 
                           where tdataseg.loadid = aif_hyp_acct_type.loadid and
                                 tdataseg.account = aif_hyp_acct_type.account and
                                 aif_hyp_acct_type.account_type in (' ','R','L','Q')
                          );

编辑:

如果没有匹配项并且该列被声明为not null,您将收到该错误。这是一个修复:

update tdataseg
    set tdataseg.amount = (select coalesce(max(decode(sign(tdataseg.amount), -1, abs(tdataseg.amount),
                                                      1,-abs(tdataseg.amount), 0)), 0)
                           from aif_hyp_acct_type 
                           where tdataseg.loadid = aif_hyp_acct_type.loadid and
                                 tdataseg.account = aif_hyp_acct_type.account and
                                 aif_hyp_acct_type.account_type in (' ','R','L','Q')
                          );

这会将不匹配设置为0。

【讨论】:

  • 谢谢。但我收到错误“ORA 01407 无法将 tdataseg.amount 更新为 null。
【解决方案2】:

我会尝试使用MERGE 语句解决此类更新问题。我觉得写起来更自然一些。

MERGE INTO tdataseg 
USING (
       SELECT loadid, account 
         FROM aif_hyp_acct_type 
        WHERE account_type IN (' ','R','L','Q')
      ) q
   ON (tdataseg.loadid=q.loadid AND tdataseg.account=q.account)
 WHEN MATCHED THEN UPDATE SET amount = - ABS(amount);

您将要更改的表格放在MERGE INTO 之后。主表在USING 查询中进行子集化。连接条件进入ON子句,实际数据变化在WHEN MATCHED THEN UPDATE SET之后指定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多