Search code examples
oracle-databaseplsqluniondeclare

Declare statement in PL/SQL for a part of the query


I have a query like the following:

select t1.varid, t1.var1, t1.var2, t1.vardata, t2.varid, t2.var1, t2,.var2 
from   table1 t1, table2 t2
where  t1.varid = t2.varid
and    t1.vardata between to_date('20170807','YYYYMMDD') and to_date('20170808','YYYYMMDD')

Now the question is: I need to extract the data not only in the data range specified in the query above, but I want to extract many other ranges in the same query.

To do that, I used UNION ALL and it works. The problem is that I have to re-write this part many times:

select t1.varid, t1.var1, t1.var2, t1.vardata, t2.varid, t2.var1, t2, var2 
from   table1 t1, table2 t2
where  t1.varid = t2.varid

Is there a tip for how to define select t1.varid... as a named variable in order to avoid a long boring repeated query?

Any other solutions are welcome.


Solution

  • As discussed in the chat you can do it as below:

    SELECT t1.varid  as col1,
           t1.var1   as col2,
           t1.var2,
           t1.vardata,
           t2.varid,
           t2.var1,
           t2,
           .var2
      FROM table1 t1, table2 t2
     WHERE     t1.varid = t2.varid
           AND t1.vardata BETWEEN TO_DATE ('20170807', 'YYYYMMDD')
                              AND TO_DATE ('20170808', 'YYYYMMDD')
            --- Give date ranges.                  
           OR   t1.vardata BETWEEN TO_DATE ('20170907', 'YYYYMMDD')
                              AND TO_DATE ('20171008', 'YYYYMMDD')                  
           OR ....
           OR ....