首页 > 解决方案 > 使用自引用窗口查询更新表

问题描述

我在尝试使用 Oracle SQL Developer 中的自引用子查询更新表时遇到问题。我相信我已经正确设置了查询,但是当我尝试运行它时,尽管所有括号都正确匹配,但我会得到一个通用的“缺少右括号”错误。

简而言之,我正在尝试更新基于 ROW_NUMBER() 函数的事务序列列,该函数对我要更新的表内的值进行分区。我已经设置了一个查询来子查询分区窗口并根据 rownum 更新表。

有没有办法我可以重新编写它以使其正常工作?我不确定是什么引发了括号错误。

update tbl a 
set transseq = (select sqtransseq from (select row_number() OVER(Partition by location order by rownum) as sqtransseq, rownum 
                from tbl ) as b
                where a.rownum = b.rownum)```
  

标签: sqloraclesql-update

解决方案


rownum不按你的想法做。我认为您将其与以下内容混淆rowid

update tbl a 
    set transseq = (select sqtransseq
                    from (select t.*,
                                 row_number() OVER(Partition by location order by location) as sqtransseq 
                          from tbl t
                         ) b
                    where a.rowid = b.rowid
                   );

但是,这是行不通的,因为rowid窗口函数是不允许的。您可以使用将 转换rowid为字符串的技巧来完成这项工作:

update tbl a 
    set transseq = (select sqtransseq
                    from (select t.*, rowidtochar(rowid) as rowid_str,
                                 row_number() over (Partition by location order by location) as sqtransseq 
                          from tbl t
                         ) b
                    where rowidtochar(a.rowid) = b.rowid_str
                   );

或者换一种说法:

update tbl a 
    set transseq = (select count(*)
                    from tbl b
                    where b.location = a.location and b.rowid <= a.rowid
                   );

推荐阅读