0

I am trying to concatenate strings that are used as column names

I want to do something like:

Select someData as "ONE" || :someVariable) from sometable;

where someVariable is a bind variable, which does not work inside double quotes. (The column should have the name "ONE2018" if someVariable = 2018.)

I tried it with single quotes and with the concat function. It doesn't work. Is there some way to accomplish this?

EDIT: With inspiration from littlefoots answer I tried

declare
  customVariable number(4);
  rc sys_refcursor;
begin
  open rc for 'select 1 as bla' || :customVariable || ' from dual';
  dbms_sql.return_result(rc);
 end;
/

which does have the output

   BLA2018
----------
         1

I don't know how to put that into a PreparedStatement, but if used on it's own it works and might help someone else

1
  • 1
    You need to use dynamic SQL to change column names. Commented Nov 20, 2018 at 11:34

1 Answer 1

2

An example based on Scott's EMP table which contains columns whose names begins with an E: ENAME and EMPNO.

You'd pass NAME or MPNO and get the result.

SQL> create or replace function f_one (par_column_name in varchar2)
  2    return sys_refcursor
  3  is
  4    l_rc sys_refcursor;
  5    l_str varchar2(200);
  6  begin
  7    l_str := 'select e' || par_column_name || ' from emp where rownum < 3';
  8    open l_rc for l_str;
  9    return l_rc;
 10  end;
 11  /

Function created.

SQL> select f_one('mpno') from dual;

F_ONE('MPNO')
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

     EMPNO
----------
      7369
      7499


SQL> select f_one('name') from dual;

F_ONE('NAME')
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

ENAME
----------
SMITH
ALLEN


SQL>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.