我有两个表:
CREATE TABLE Test_Persons_A (
PersonID int,
LastName varchar(255),
FirstName varchar(255)
);
INSERT INTO Test_Persons_A
(PersonID,LastName,FirstName)
values(11,'LN_A1','FN_A1');
INSERT INTO Test_Persons_A
(PersonID,LastName,FirstName)
values(12,'LN_A2','FN_A2');
CREATE TABLE Test_Persons_B (
PersonID int,
LastName varchar(255),
FirstName varchar(255)
);
INSERT INTO Test_Persons_B
(PersonID,LastName,FirstName)
values(21,'LN_B1','FN_B1');
INSERT INTO Test_Persons_B
(PersonID,LastName,FirstName)
values(22,'LN_B2','FN_B2');
commit;
但是后来我不知道如何对随后的“ WITH”进行条件选择:
------------------------------use IF, not working ------------------------------
var TEST_TBL varchar2(20);
exec :TEST_TBL := 'test_person_A';
with Test_tbl as
(
IF UPPER(:TEST_TBL) = 'TEST_PERSONS_A' then select * from Test_Persons_A;
ELSIF UPPER(:TEST_TBL) = 'TEST_PERSONS_B' then select * from Test_Persons_B;
End if;
)
select PersonID as PID, LastName as LN, FirstName as FN
from Test_tbl tp
where tp.LASTNAME like '%1%'
------------------------------use CASE, not working ------------------------------
var TEST_TBL varchar2(20);
exec :TEST_TBL := 'test_person_A';
with Test_tbl as
(
CASE WHEN UPPER(:TEST_TBL) = 'TEST_PERSONS_A' then
select * from Test_Persons_A;
ELSE
select * from Test_Persons_B;
End
)
select PersonID as PID, LastName as LN, FirstName as FN
from Test_tbl tp
where tp.LASTNAME like '%1%';
最终,我可以以某种方式概括一下吗?即在SQL(至少是Oracle)中,我可以在哪里断言条件语句,而我不能在哪里断言?
答案 0 :(得分:3)
使用union all
:
with Test_tbl as (
select *
from Test_Persons_A
where upper(:TEST_TBL) = 'TEST_PERSONS_A'
union all
select *
from Test_Persons_B
where UPPER(:TEST_TBL) = 'TEST_PERSONS_B'
)
这假定表具有相同顺序的相同列。
如果它们没有相同的列,请列出其余代码所需的特定列,也许将NULL
分配给可能不在其中一个表中的列。