Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column name as variable in PL/SQL ORACLE

Tags:

oracle

plsql

I want to have a code where i would declare a column name as variable and then use this variable to retrieve desired column from a certain table.

DECLARE
col_n VARCHAR (100) := 'X' ;
BEGIN
select col_n from my_table;
END;

What is the most easy and explicit way for that in Oracle?

like image 662
griboedov Avatar asked Aug 07 '14 12:08

griboedov


2 Answers

You can use dynamic sql to execute a query that you construct as a string. It would go something along these lines:

DECLARE
col_n VARCHAR (100) := 'X' ;
plsql_block VARCHAR2(500);
BEGIN
    plsql_block := 'select ' || col_n  || ' from my_table';
    EXECUTE IMMEDIATE plsql_block;
END;
like image 169
Klaus Byskov Pedersen Avatar answered Sep 28 '22 19:09

Klaus Byskov Pedersen


You can use dynamic sql:

DECLARE
  col_n VARCHAR (100) := 'X' ;
  l_cursor sys_refcursor;
  l_temp number(10); -- won't work if the col_n column has different type
BEGIN
  open l_cursor for 'select '|| col_n ||' from my_table';
  loop
    fetch l_cursor into l_temp;
    exit when l_cursor%NOTFOUND;
    ...
  end loop;
END;

The problems is you have to know for sure the type of your column.

Actually, there is one more way to do it, if you use SQL*Plus environment:

SQL> select &&col_n from employees where &&col_n = 199;
Enter value for col_n: employee_id
old   1: select &&col_n from employees where &&col_n = 199
new   1: select employee_id from employees where employee_id = 199

EMPLOYEE_ID
-----------
        199
like image 31
neshkeev Avatar answered Sep 28 '22 17:09

neshkeev