简体   繁体   中英

Oracle SQL: in 'WITH' statement, how to do conditional select, use IF or CASE?

I have two tables:

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;

But then I can't figure out how to do a conditional select for the 'WITH' that follows:

------------------------------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%';

And ultimately, can I generalize this somehow? ie In SQL (oracle at least) where can I assert conditional statements, and where can't I?

Use 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'
     )

This assumes the tables have the same columns in the same order.

If they don't have the same columns, list the specific columns you want for the remaining code, perhaps assigning NULL to columns that might not be in one of the tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM