Sql 如果表中不存在第一个字段,请查看同一表中的其他字段
是否有方法从表中选择字段,如果该字段不存在,则从同一表中选择其他字段?例如:Sql 如果表中不存在第一个字段,请查看同一表中的其他字段,sql,oracle,Sql,Oracle,是否有方法从表中选择字段,如果该字段不存在,则从同一表中选择其他字段?例如: SELECT MY_FIELD from MY_TABLE 错误:MY_字段:无效标识符 是否有方法检查它是否存在,如果存在,则使用该字段进行查询,如果不存在,则使用示例: SELECT my_field2 from client. 我的问题是 我正在编写一份将在两个数据库上使用的报告,但根据数据库的不同,字段名有时可能会略有不同。这不会编译,所以-我不这么认为。您可以尝试使用动态SQL,它读取用户选项卡列的内容,
SELECT MY_FIELD from MY_TABLE
错误:MY_字段:无效标识符
是否有方法检查它是否存在,如果存在,则使用该字段进行查询,如果不存在,则使用示例:
SELECT my_field2 from client.
我的问题是
我正在编写一份将在两个数据库上使用的报告,但根据数据库的不同,字段名有时可能会略有不同。这不会编译,所以-我不这么认为。您可以尝试使用动态SQL,它读取用户选项卡列的内容,并动态创建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;
您真正需要做的是与您的管理/开发领导谈谈为什么不同的数据库不协调。但是,由于这是一个编程站点,这里有一个使用动态SQL的编程答案 正如已经指出的,您可以在不同的数据库中创建视图,为自己提供一个统一的查询层。如果无法创建视图,可以执行以下操作:
create table test ( present_column NUMBER );
insert into test select rownum * 10 from dual connect by rownum <= 5;
declare
l_rc SYS_REFCURSOR;
begin
BEGIN
OPEN l_rc FOR 'SELECT missing_column FROM test';
EXCEPTION
WHEN others THEN
OPEN l_rc FOR 'SELECT present_column FROM test';
END;
-- This next only works in 12c and later
-- In earlier versions, you've got to process l_rc on your own.
DBMS_SQL.RETURN_RESULT(l_rc);
end;
这比协调数据库或创建视图的其他解决方案要差。首先,这种方式不会对查询进行编译时检查。这可以在使用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
如果您希望看到它运行,请使用SQL FIDLE。如何创建视图?这样可以查询视图而不是表,避免了变量列名的问题。另一种方法可以是动态SQL,但您需要PLSQL,而不仅仅是普通SQL。