A
A
Almik Oh! Give me a guitar2015-08-12 08:21:40
Oracle
Almik Oh! Give me a guitar, 2015-08-12 08:21:40

Oracle Pl/SQL: Is it possible to refer to a table column via varchar2?

Hello!
There is a function in PLSQL where, depending on the parameter, I must search for certain columns.
Let's say if academ_level_id = 1 , then I should search on the COLUMN1 column.
The experimental table is something like this my_settingse_rule( ID , COLUMN1 ,COLUMN 2 )
But in fact there are 10 such COLUMN pieces! plus must be combined with other conditions

CREATE OR REPLACE FUNCTION get_setting_min( id number , academ_level_id IN academic_level.academiclevelid%type)
  RETURN number
IS
  l_min number;
  a_to_use VARCHAR2(80);
BEGIN

  CASE academ_level_id
    WHEN 1 THEN a_to_use := 'COLUMN1';
    WHEN 2 THEN a_to_use := 'COLUMN2';
    ELSE a_to_use := 0;
  END CASE;
  select rsre.TERM_MIN
      into l_min
      from my_settingse_rule rsre 
      where  rsre.a_to_use = 1 and rsre.id = id;
 return l_min;
END ;

where rsre.a_to_use = 1 and rsre.id = id;
The code doesn't work, it throws an error.
Error(45,39): PL/SQL: ORA-00904: "RSRE"."A_TO_USE": invalid identifier

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
pesenka1, 2015-08-12
@almyk

docs.oracle.com/cd/E11882_01/appdev.112/e25519/dyn...

A
Alexey Skahin, 2015-08-12
@pihel

Well, or so, without execute immediate

select rsre.TERM_MIN
      into l_min
      from my_settingse_rule rsre 
      where  rsre.id = id
      and 
      ( (rsre.COLUMN1 =1 and academ_level_id =1) or (rsre.COLUMN2 =1 and academ_level_id =2) or academ_level_id > 2 )

A
Alexander Podrezov, 2015-08-18
@alpodrezov

If there are many fields and the query can change depending on the conditions, then use dynamic sql
execute immediate 'select * from ' || table_name || 'a' || 'where a.' || column_name;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question