使用新表对数据库进行向后兼容的 SQL 查询

问题描述 投票:0回答:1

我们有几个 Oracle 数据库,假设我们创建表

t
,其中一些包含列
a
b

如何开发可以针对所有数据库成功运行的 SQL 查询

  • 在带有表的数据库上
    t
    它的行为就像
    select a, b from t
  • 在没有表的数据库上
    t
    它返回带有列
    a
    b
    的空结果集。

这是看似不可能的查询中的另一个查询(请参阅herehere)。目的是克服数据库部署过程中数据库存在差异的某些时期。清理客户端应用程序中的差异相对比临时解决方案更费力 - 但有点hacky - 解决方案。

sql oracle backwards-compatibility oracle19c
1个回答
0
投票

解决方案是利用 XML 特性。最终结果集始终从 XML 重新创建。 XML 要么是根据真实数据构建的,要么是伪造的,具体取决于数据库目录中有关表存在的信息。

create table t as select 'a' as a, 'b' as b from dual
with singlexml(xmlcol) as (
  select xmltype(nvl(
           dbms_xmlgen.getxml('select * from ' || (
             select case count(*) when 0 then 'dual where 0=1' else max(t.table_name) end
             from all_tables t
             where t.table_name = 'T' -- change to X for testing nonexistent table
           ))
           , '<?xml version="1.0"?><ROWSET/>'
         )) 
  from dual
)
select cols.a
     , cols.b
from singlexml
   , xmltable('/ROWSET/ROW'
              passing singlexml.xmlcol
              columns a varchar2(32) path 'A'
                    , b varchar2(32) path 'B'
     ) cols

A B
a b

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.