views:

136

answers:

3

I have a table with columns named with the number of hour of day like this:

col00 NUMBER(5)
col01 NUMBER(5)
col02 NUMBER(5)
...
col23 NUMBER(5)

...and I have another query that returns a count by hour.

I want to recover the colXX value by hour.... then I can recover with "decode" or "case when..." but I want know if exists any way to recover the column by a text like this:

select "col"||hour from table;

in the hypothetical above example if hour is 13 then would be translated like:

select col13 from table;

there is any way to do this ?

+3  A: 

You have to use dynamic SQL:

EXECUTE IMMEDIATE 'SELECT col'|| hour || ' FROM TABLE;'

Reference:

OMG Ponies
I know the execute immediate but i need it in a subquery. NOT a PL block.
glaudiston
@glaudiston: You can't - either the entire query is dynamic SQL, or you make a function (or stored procedure) to return the value based on this dynamic SQL.
OMG Ponies
A: 

While it looks a little...brute force...you could use a bunch of UNION statements between queries:

SELECT col00
  FROM TABLE 
 WHERE to_char(SYSDATE, 'HH24') = '00'
UNION
SELECT col01
  FROM TABLE 
 WHERE to_char(SYSDATE, 'HH24') = '01'
UNION
SELECT col02
  FROM TABLE 
 WHERE to_char(SYSDATE, 'HH24') = '02'  
   (...and so on...)
UNION
SELECT col23
  FROM TABLE 
 WHERE to_char(SYSDATE, 'HH24') = '23' 
Mark B.
It's not what i'm looking for... but thks anyway.
glaudiston
thanks for response, but i found a way more flexible with dbms_xml.getxml('query'). in this way I can generate the query and get its result.
glaudiston
select dbms_xml.getxml('SELECT col'|| to_char(sysdate,'HH24') || ' FROM TABLE;') from dual;
glaudiston
A: 

Closing...

select REGEXP_REPLACE( REGEXP_REPLACE( DBMS_XMLGEN.GETXML(' SELECT col'|| to_char(sysdate,'HH24') || ' FROM TABLE '),'.<[/]?(\?xml .>|ROW).',''),' (<([^>])>([^<])]>.*)','\2=\3') AS RES from dual

its not so simple but very flexible and works great for me.

glaudiston