我需要从表 Table_A 中选择列,但是还有另一个表具有相同的模式 Table_B。查询应动态确定来自表。例如。如果 Table_A 有更多行,则使用 Table_A,否则使用 Table_B。
查询类似这样的内容 select employee,salary,id from ( condition to count rows and select the table )table;
这是否可能不使用游标和立即执行??。
我需要从表 Table_A 中选择列,但是还有另一个表具有相同的模式 Table_B。查询应动态确定来自表。例如。如果 Table_A 有更多行,则使用 Table_A,否则使用 Table_B。
查询类似这样的内容 select employee,salary,id from ( condition to count rows and select the table )table;
这是否可能不使用游标和立即执行??。
通常,您会为这类事情使用动态 SQL。这将涉及使用DBMS_SQL
包EXECUTE IMMEDIATE
或执行OPEN <<cursor>> FOR <<SQL statement string>>
.
如果您真的想使用静态 SQL,您可以查询两个表并只返回一组结果。我无法想象这种情况会真正有意义,但你当然可以做到
创建一个FOO
和一个FOO2
表。 FOO2
从两排到一排FOO
SQL> create table foo( col1 number );
Table created.
SQL> create table foo2( col1 number );
Table created.
SQL> insert into foo values( 1 );
1 row created.
SQL> insert into foo2 values( 1 );
1 row created.
SQL> insert into foo2 values( 2 );
1 row created.
运行查询。这将返回所有数据FOO2
SQL> ed
Wrote file afiedt.buf
1 select col1
2 from (select the_union.*,
3 max(cnt) over () max_cnt
4 from (select col1, count(*) over () cnt from foo
5 union all
6 select col1, count(*) over () from foo2) the_union)
7* where cnt = max_cnt
SQL> /
COL1
----------
1
2
将更多行插入FOO
. 现在相同的查询将返回所有数据FOO
SQL> insert into foo values( 3 );
1 row created.
SQL> insert into foo values( 5 );
1 row created.
SQL> commit;
Commit complete.
SQL> select col1
2 from (select the_union.*,
3 max(cnt) over () max_cnt
4 from (select col1, count(*) over () cnt from foo
5 union all
6 select col1, count(*) over () from foo2) the_union)
7 where cnt = max_cnt;
COL1
----------
1
3
5
但是,正如我所说,我无法理解这样做实际上有意义的情况。
我完全猜测您真正想要做什么,但我认为您想使用同义词。我猜当您应该使用 TableA 与 TableB 时,会触发某种事件。创建一个指向 TableA 的同义词“my_table”并让您的视图从“my_table”中选择。然后,每当您希望视图指向 TableB 时,只需将同义词切换为指向 TableB,您无需对视图执行任何操作。
有关更多信息,请阅读概念指南中的同义词。