1

I am trying to make a sub-table that "stores" a decode between two values, because I need to use that decode multiple times. Let's say these are my tables:

Table Person
Name    Number_name
Jeremy  One
Thomas  Two
Stephen Three

my current SQL looks like this:

SELECT
    decode (number_name,
    'one',1,
    'two',2,
    'three',3,
    'four',4)
    num
    FROM person where name = 'Jeremy'
    and (some other condition)
UNION SELECT
    decode (number_name,
    'one',1,
    'two',2,
    'three',3,
    'four,4)
    num
    FROM Person
    where Name <> "Jeremy"
    and (some other condition)

What I'd like to be able to do is something like this:

SELECT num from my_temp_table where name = "Jeremy" and (some other condition)
union select num from my_temp_table where name <> "Jeremy" and (some other condition)
...

where my_temp_table is constructed during that query (it ceases to exist when the query finishes running) and will look like

Table my_temp_table
Name  num
One   1
Two   2
Three 3
Four  4

And hopefully I can do this without the ol' "select one name,1 num from dual union all ..."

Is this doable?

Jeremy
  • 5,365
  • 14
  • 51
  • 80

1 Answers1

5

The WITH clause is sounds like the closest thing to what you're describing. But that requires that you generate the data somehow. Selecting from DUAL is likely the easiest option

WITH my_temp_table AS (
  SELECT 'One' name, 1 num from dual union all
  SELECT 'Two', 2 from dual union all
  SELECT 'Three', 3 from dual union all
  SELECT 'Four', 4 from dual
)
SELECT *
  FROM my_temp_table 
       JOIN person ON (<<some join condition>>)
 WHERE <<some predicate>>

Since you don't want to union a bunch of queries, you could do something like

WITH my_temp_table AS (
  select level num,
         initcap( to_char( to_date( level, 'J' ),
                           'JSP' )) name
    from dual
 connect by level <= 4
)
...
Justin Cave
  • 227,342
  • 24
  • 367
  • 384