根据参数生成联合sqls

时间:2014-06-13 07:15:11

标签: sql oracle

我想编写带有参数和基于参数的sql 创建一个带参数表联合的视图

目前我在下面做,但客户表的范围从R1到R40

create or replace view customers_a as 
select * from customer_R1 
UNION 
select *  from customer_R40;

现在我需要的是编写将参数作为

的sql
@gen.sql R1 R3 R4

并创建视图

create or replace view customers_ALL as 
select * from customer_R1 
UNION 
select *  from customer_R3
UNION 
select *  from customer_R4;

取决于传递的参数,它应该是动态的

1 个答案:

答案 0 :(得分:1)

你考虑过这个吗?

create or replace view customers_ALL as 
    select 'R1' as which, c.* from customer_R1 c
    UNION ALL
    select 'R2' as which, c.* from customer_R1 c
    UNION ALL
    select 'R3', c.* from customer_R3 c
    UNION ALL
    . . .
    select 'R31', *  from customer_R31 c;

然后您可以使用以下方式查询此视图:

select *
from customers_ALL
where which in ('R1', 'R3', 'R4')

这假设表中没有重复项。否则,引入which会使行唯一(这就是我将union更改为union all的原因。)