Tuesday, January 29, 2013

SQL Trick - Always Return a Row



This SQL will always return a pre-defined row if none exist.  "no rows selected" was getting really old.

prompt
prompt ###############
prompt INVALID OBJECTS
prompt ###############
col owner       heading 'Owner'  format a15
col object_type heading 'Type'   format a20
col object_name heading 'Object' format A30
with t as (
select owner,
       object_type,
       object_name
from   dba_objects
where  status = 'INVALID'
order by owner,
         object_type,
         object_name)
select owner, object_type, object_name from (
   select rownum rn, owner, object_type, object_name
     from t
   union
   select 0, '~~All VALID~~', '~~All VALID~~', '~~All VALID~~' from dual
   order by 1 desc
   )
  where (rn > 0 or (rownum = 1 and rn = 0))
/

Sample Output when no rows are returned:
Owner           Type                 Object
--------------- -------------------- ------------------------------
~~All VALID~~   ~~All VALID~~        ~~All VALID~~

No comments:

Post a Comment