Saturday, October 15, 2011

Query at ReportExtract

While working on report extract, came across a situation which I thought can not be handled using simple sql query and needs to write pl-sql block; but Sandesh Birwatkar gave a simple solution.

Solution is quite simple, but I never thought of that..

As an example, below is the scenario

You have an employee table, and user will give department number and from which you need to fetch out the respective employees.

select *
from employees
where department_id in (
select distinct department_id
from departments
where department_id = '&DepID'
)

But, twist is, if department table do not have any records, query should return all employee records.

How will you do it? below is the solution

create table departmentsBKP
as
select * from departments

select *
from employees
where department_id in (
select distinct department_id
from departmentsBKP
where department_id = '&DepID'
)
union
select *
from employees
where 0 = (select count(*) from departmentsBKP)

delete from departmentsBKP

and now again if u fire select statement, you will get all records of employees table.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. select *
    from emp
    where deptid in ( select distinct deptid
    from dept where deptid = '&depno' )
    union
    select *
    from emp
    where not exists ( select 1
    from dept
    where deptid = '&depno' )

    ReplyDelete

All about CSS

From book HTML & CSS - Design and Build Websites - Jon Duckett CSS works by associating rules with HTML elements. These rules govern how...