如果第一个字段不存在于表中,则查看同一个表中的其他字段

时间:2018-06-07 12:01:05

标签: sql oracle

有没有办法从表中选择一个字段,如果该字段不存在,那么从同一个表中选择一个不同的字段?例如:

SELECT MY_FIELD from MY_TABLE
  

错误:" MY_FIELD":无效标识符

有没有办法检查它是否存在,如果它确实存在然后使用该字段进行查询,如果它不存在则使用示例:

SELECT my_field2 from client.

我的问题是 我正在编写一个将在两个数据库上使用的报告,但有时根据数据库的不同,字段名称可能略有不同。

3 个答案:

答案 0 :(得分:3)

您真正需要做的是与您的管理/开发主管讨论为什么不同的数据库不协调。但是,由于这是一个编程站点,这里是使用动态SQL的编程答案。

正如已经指出的那样,您可以在不同的数据库中创建视图,为自己提供一个统一的查询层。如果您无法创建视图,可以执行以下操作:

import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation

HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
    ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
    if (annotation != null) {
        return annotation.value();
    }
    return HttpStatus.INTERNAL_SERVER_ERROR;
}

这不如其他解决方案(协调数据库或创建视图)。首先,您没有以这种方式检查查询的编译时间。

答案 1 :(得分:1)

那不会编译,所以 - 我不说。您可以尝试使用动态SQL来读取USER_TAB_COLUMNS的内容并在运行中创建SELECT语句。

取决于您使用的报告工具,可能(或可能不)。例如,Apex提供(作为报告的来源)一个返回查询的函数,因此您可以在那里使用它。

我建议一个更简单的选项 - 在具有统一列名的两个数据库上创建视图,以便您的报告始终从视图中选择并始终有效。例如:

-- database 1:
create view v_client as
  select client_id id,
         client_name name
  from your_table;

-- database 2:
create view v_client as
  select clid id,
         clnam name
  from your_table;

-- reporting tool:
select id, name
from v_client;

答案 2 :(得分:1)

这可以使用DBMS_XMLGEN.GETXML在单个SQL语句中完成,但它会变得混乱。使用动态SQL或视图可能更简洁,但有时候很难创建支持对象。

样本表:

--Create either table.
create table my_table(my_field1 number);
insert into my_table values(1);
insert into my_table values(2);

create table my_table(my_field2 number);
insert into my_table values(1);
insert into my_table values(2);

查询:

--Get the results by converting XML into rows.
select my_field
from
(
    --Convert to an XMLType.
    select xmltype(clob_results) xml_results
    from
    (
        --Conditionally select either MY_FIELD1 or MY_FIELD2, depending on which exists.
        select dbms_xmlgen.GetXML('select my_field1 my_field from my_table') clob_results
        from user_tab_columns
        where table_name = 'MY_TABLE'
            and column_name = 'MY_FIELD1'
            --Stop transformations from running the XMLType conversion on nulls.
            and rownum >= 1
        union all
        select dbms_xmlgen.GetXML('select my_field2 my_field from my_table') clob_results
        from user_tab_columns
        where table_name = 'MY_TABLE'
            and column_name = 'MY_FIELD2'
            --Stop transformations from running the XMLType conversion on nulls.
            and rownum >= 1
    )
    --Only convert non-null values.
    where clob_results is not null
)
cross join
xmltable
(
    '/ROWSET/ROW'
    passing xml_results
    columns
        my_field number path 'MY_FIELD'
);

结果:

MY_FIELD
--------
1
2

Here's一个SQL小提琴,如果你想看到它正在运行。

相关问题