Using Column Name returned by function in SELECT statement

Hi
Output from my function (RETURN data type is VARCHAR2) is column name. I want to use it directly in my SELECT statement. Below is simplified example of this:
--- Function
CREATE OR REPLACE FUNCTION simple RETURN varchar2 IS
BEGIN
RETURN ‘my_column’;
END simple;
--- Select
SELECT simple FROM my_table;
This does not work. It seems that output from function is passed in quotation i.e.
SELECT ‘my_column’ FROM my_table;
So the output from SELECT is a list of rows populated with values my_table:
COLUMN     simple
ROW1     my_column
ROW2     my_column
ROW3     my_column
Can please someone help me with this?

I'm not sure I got you right.
In standard SQL everything must be known at compile time. If not dynamic SQL is required, but is a costly operation (usually requires parsing before each execution) so it should better not be used when standard SQL can do it.
I provided a design time example where a function returns the column name from the given the table name and column id for a varchar2 column data type to make things simple. Then a query string is constructed and executed dynymically to return all column values of the chosen table_name.column_name.
SELECT simple FROM my_tableAt compile time the simple function return value is unknown (any varchar2 value would do) you already find out you get the (same) return value (i.e column name) for each table row => dynamic SQL needed to get the column values
The purpose of function would be to rename all columns for provided table.The table name would be provided, right? If yes => dynamic SQL
What is the function supposed to return the column name (where would the new name come from?), the column alias (which table column would be renamed to the new name?)
The user could use the new_column name as the column alias name submitting the query.
Is it possible to do this?Maybe () using a pipelined function (different data types - number,date, ... not cosidered yet) but your simple query;
<tt>SELECT simple FROM my_table</tt>
might look like:
<tt>select my_column_value new_column_name from table(get_column_value(table_name,column_name))</tt>
Sorry, no Database at hand to provide a specific example.
Regards
Etbin

Similar Messages

  • Output of value returned from function in SELECT statement ??

    Hi
    I have created the below function
    create or replace
    FUNCTION jc_test
    RETURN VARCHAR2
    IS myrec VARCHAR2(270);
    BEGIN
    SELECT RPAD('*',270,'*')
    INTO myrec
    FROM DUAL ;
    RETURN myrec;
    END ;
    and I executed the SELECT statement in Oracle SQL developer as a script
    select
    LENGTH(jc_test()) len
    *,jc_test() rec*
    from dual ;
    I get exact output as below
    LEN REC
    270 ******************************************************************************************************************************************************************************************************************************************************************************
    So here LEN is correctly shown as 270 characters but when I see the astrisk's (also appended with spaces ) its total length is 4000 characters
    Can anyone give their thoughts on this.
    Its fine if I run as normal, i mean not as a script.
    Regards
    jc
    Edited by: JC on Jun 16, 2011 11:25 AM

    Hi,
    So here LEN is correctly shown as 270 charactersYes, correct
    but when I see the astrisk's (also appended with spaces ) its total length is 4000 charactersNo buts. It is not padded. That is just how it is displayed by your tool. In SQL*Plus this is controlled by LINESIZE and COLUMN
    SQL> create or replace function dummy return varchar2 as begin return null; end;
      2  /
    Function created.
    SQL> select dummy from dual;
    D
    X
    SQL> select dummy() from dual;
    DUMMY()
    SQL> col "dummy()" for a10
    SQL> select dummy() from dual;
    DUMMY()
    SQL>P.S: It is a really bad idea to create your own wrapper functions, built-in functions. Hopefully you are not really doing that?
    Regards
    Peter

  • Need to return dynamic column names for a function returning nested table

    I am having a pl/sql function which is returning a nested table.
    For this i have defined an object which is having 4 attributes- 1 number type, 3 varchar2 type -p1,p2,p3.
    My function is taking input parameter v1,v2,v3 all of varchar2 type.Inside the function body,i am using these (v1,v2,v3) to filter data from an sql query and i am also
    using pivot function in this sql query.
    At the end my function is returning the object as defined in the starting .
    When i am excuting this function,thru select statement :
    select * from table(f1_test('A','B','C'));
    i am geting p1,p2,p3 as column name ,which are names used when i had defined object type.Instead i want column name to be dynamic (wotever i am passing in function as
    parameter while executing the function ,here A,B,C)
    Please help me in geting column names dynamic as passed in input parameter (i.e A,B,C for this case )
    Sample code for the problem:
    create or replace TYPE obj1 AS OBJECT
    ( id number(5,0)
    ,p1 varchar2(10),
    ,p2 varchar2(10)
    ,p3 varchar2(10)
    create or replace TYPE tt1 AS TABLE OF OBJ1;
    create or replace
    function f1_test (v1 varchar2,v2 varchar2,v3 varchar2)
    return tt1 as
    v_return tt1 ;
    v_str varchar2(30000);
    begin
    v_str:='
    select
    cast(
    multiset(
    select * from
    select
    aa.report_id
    ,cc.name
    ,e.amount
    from
    aa,cc,e
    where
    <join conditions>
    and cc.name in ('''||v1||''','''||v2||''','''||v3||''')
    pivot (sum (amount) for name in ('''||v1||''' as '||v1||','''||v2||''' as '||v2||','''||v3||''' as '||v3||'))
    as tt1)
    from
    dual';
    dbms_output.put_line(v_str);
    execute immediate v_str
    into
    v_return ;
    return v_return;
    end;
    Edited by: 845831 on 20 Mar, 2011 12:15 PM

    select id,p1 A,p2 B,p3 C from table(f1_test('A','B','C'));
    drop function f1_test;
    drop type tt1;
    drop type obj1;
    create or replace TYPE obj1 AS OBJECT
    ( id number(5,0)
    ,p1 varchar2(10)
    ,p2 varchar2(10)
    ,p3 varchar2(10)
    create or replace TYPE tt1 AS TABLE OF OBJ1;
    CREATE OR REPLACE
      FUNCTION f1_test(
          v1 VARCHAR2,
          v2 VARCHAR2,
          v3 VARCHAR2)
        RETURN tt1
      AS
        v_return tt1 ;
        v_str VARCHAR2(30000);
      BEGIN
        v_str:='select cast(multiset(select 1,''20'',''30'',''40'' from dual) as tt1) from dual';
        dbms_output.put_line(v_str);
        EXECUTE immediate v_str INTO v_return ;
        RETURN v_return;
      END;
    /

  • Incorrect column names returned using OCIDescribeAny

    I am trying to retrieve column names using OCIDescribeAny and OCIAttrGet api calls.
    The column names and the lengths of the column names returned by OCIAttrGet calls are usually correct.
    Except when the length of column names are divisible by 4, an extra tab is padded at the end of the returned string by OCIAttrGet.
    The length returned by the call is fine.
    Example 1.
    Column Name:
    CITY
    Results Returned by OCIAttrGet:
    column name: CITY\t
    column length: 4
    Example 2.
    Column Name:
    PHONE_NUMBER
    Results Returned by OCIAttrGet:
    column name: PHONE_NUMBER\t
    column length: 12
    Does anyone has experience with this?
    Edited by: simon780 on Mar 13, 2010 2:48 PM
    Edited by: simon780 on Mar 13, 2010 4:03 PM

    Thank you for answering my question, I thought I was doing something wrong, since this is my very first time using oci.
    I do see non-null terminated strings mentioned from places to places on the oracle docs, but I don't see it mentioned specifically on the attribute OCI_ATTR_NAME.
    Anyway, as long as I have the string length returned by the function call, then it's all good. Thank you again!!

  • Using java function in select statement

    Hi,
    I am trying to use java function in select statement.
    public class ClassA{
         private static String MyConst = "foo";
         public static String functionA(){
              return MyConst;
    in my query I have:
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    ClassA is part of the application (no need to import).
    I get and error of Invalid Expression on ClassA.functionA().
    I also tried to declare the function in the processor element:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    <wlevs:processor>
    but then I get a different error in the processor XML file:  "An InvocationTargetException was encoutered while attemting to register the user defind function A. The message was null"
    What am I missing here?

    Hi,
    From the above description, you have tried two manners to call method functionA() in the user defined  class ClassA. One uses java cartridge manner directly and the other try to use user defined function manner.
    For the java cartridge manner, the following CQL query should work if the ClassA is really included in the OEP app. I have done similar test before, it works.
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    For user defined function manner, I think two things you need to change:
    1. Need to declare the function in the EPN assembly file(under META-INF/spring/), not component configuration file(under META-INF/wlevs/). The following is an example:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    </wlevs:processor>
    2. Call the user defined function in the CQL query in the component configuration file under processor. For example:
    select A() from myChannel
    Regards,
    XiYing

  • Can we use Column Names in Parameter Cursor

    Hi
    can we use Column Names in Parameter Cursor??
    DECLARE
    CURSOR Emp_Cur (P_Deptno NUMBER)
    IS
    SELECT Empno, Ename
    FROM Emp
    WHERE Deptno = P_Deptno;
    BEGIN
    FOR Emp IN Emp_Cur(10)
    LOOP
    DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
    DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
    END LOOP;
    FOR Emp IN Emp_Cur(20)
    LOOP
    DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
    DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
    END LOOP;
    END;
    In the above Program, I send Deptnumber. If i send Column names like Empno, Ename. What can i do??
    If Declare Samething Through Parameter Cursor, it doesn't accept VARCHAR2(Size)

    For parameters you don't use size, just the type (DATE, NUMBER, VARCHAR2, CLOB, ...)
    DECLARE
      CURSOR Emp_Cur (P_Ename VARCHAR2)
      IS
        SELECT Empno, Ename
        FROM Emp
        WHERE Ename = P_Ename;
    BEGIN
      FOR Emp IN Emp_Cur('SCOTT')
      LOOP
        DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
        DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
      END LOOP;
    END;

  • How to pass rowtype argument to a function from select statement?

    Hi all!
    I have function that takes mytable%rowtype as in parameter. can I pass entire row of mytable to the function from select statement? kind of
    select myfunction(mytable.*) from mytable where ....
    Thanks in advance

    The function can be used in a SQL statement only if it accepts SQL types and returns SQL type. %ROWTYPE being PL/SQL construct and not a SQL datatype, can not be used in this context.
    http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10743/datatype.htm#i2093

  • PL/SQL Function in Select statement

    Hi
    I am calling a function in select statement. The query works in Toad and PL/SQL developer except SQL plus and disconnecting Oracle connection.
    The error is “ERROR at line 1: ORA-03113: end-of-file on communication channel”.
    When I called the same query from BC4J View Object the error message is “java.sql.SQLException: No more data to read from socket”.
    Can any one advise me please?
    Thanks
    Srini

    Srini
    I've seen similar cases in the past with 9.2.0.x (x <= 5). What Oracle version are you using? It's worth checking the bug database (I can't just now - I don't have a valid support id in my current contract). And as Warren says, post your SQL query.
    HTH
    Regards nigel

  • Unable to call local function in select statement.

    Hi all,
    I am unable to call the local function in select statement in below scenario.
    DECLARE
    l_cnt NUMBER;
    FUNCTION FUN1 RETURN NUMBER
    AS
    BEGIN RETURN 2;
    END;
    BEGIN
    SELECT FUN1 INTO l_cnt FROM DUAL;
    DBMS_OUTPUT.PUT_LINE(l_cnt );
    END;
    /Any alternate way to call local function in select statement?
    Thanks
    Ram.

    Hi,
    Sorry, you can't call a locally defined function in a SQL statement, even if that SQL statement is in a PL/SQL block where the function is in scope.
    This applies to packages, also. If a function is not declared in the package spec, but only in the package body, then you can't call it from SQL statements in the package body.
    Why do you want a locally defined function? Why not a function defined outside the procedure?

  • How to use column name as variable in select statement

    hi,
    i want to make a sql query where in select statement using variable as a column name. but its not working plz guide me how can i do this.
    select :m1 from table1;
    regards

    Hi,
    Is this what you want..
    SQL> select &m1 from dept;
    Enter value for m1: deptno
    old   1: select &m1 from dept
    new   1: select deptno from dept
        DEPTNO
            10
            20
            30
            40
    SQL> select &m1 from dept;
    Enter value for m1: dname
    old   1: select &m1 from dept
    new   1: select dname from dept
    DNAME
    ACCOUNTING
    RESEARCH
    SALES
    OPERATIONS
    SQL> select &&m1 from dept;
    Enter value for m1: loc
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTON
    SQL> select &&m1 from dept;
    old   1: select &&m1 from dept
    new   1: select loc from dept
    LOC
    NEW YORK
    DALLAS
    CHICAGO
    BOSTONIf you use single '&' then each time you fire the query, It will ask for the new value..
    But if you will use double '&&' the value of m1 will be persistent across the session..
    Twinkle

  • Using TRIM function in select statement

    Hi All,
    I'm using the TRIM function in my select statement to eliminate the white spaces.
    But while using in select the TRIM function is not working in SQL*PLUS client(The query returns the white spaces also)
    Kindly provide some pointers regarding the issue.........
    I want to get only the data without the spaces in select statement
    Regards,
    Mohan

    Hi, Mohan,
    SQL*Plus always pads columns to make them line up nicely.
    If you have a column declared as VARCHAR2 (20), then SQL*Plus will normally display 20 characters for that column, even in the maximum actual length is, say, 5 (or even if the column always happens to be NULL).
    If you want the output to include only the actual data, without the padding that SQL*Plus adds, then concatenate all the columns into one big string column.
    People often do something like the following to generate a CSV file, with no exta spaces:
    SELECT       TO_CHAR (empno)
    || ',' || ename
    || ',' || job
    || ',' || TO_CHAR (deptno)
    || ',' || TO_CHAR (hiredate, 'DD-Mon-YYYY')     AS all_data
    FROM          scott.emp;

  • Determining Column name involve in Functional Index

    I write this query to know about the existing indexes of all tables pertains to a schema. My problem is when index is functional one, column name is not descriptive, it is like SYS_NC00047$, ..... as yet i could not find the way to know exact column name in the out put of this query. your help is required..
    SELECT index_owner,
             index_name,
             table_owner,
             table_name,
             column_name,
             column_position,
             column_length
        FROM dba_ind_columns
       WHERE index_owner = 'CORE_BUSINESS'
    ORDER BY table_name               ;

    Use DBA_IND_EXPRESSIONS or USER_IND_EXPRESSIONS.
    See this example :
    SQL> drop table X_1 purge;
    Table dropped.
    SQL>  create table X_1 (col_1  varchar2(5), col_2 number);
    Table created.
    SQL> create index X_1_UPPER_COL_1 on X_1(upper(col_1));
    Index created.
    SQL> set long 20000
    SQL> select column_expression from user_ind_expressions
      2  where index_name = 'X_1_UPPER_COL_1';
    COLUMN_EXPRESSION
    UPPER("COL_1")
    SQL>Note : COLUMN_EXPRESSION is a LONG datatype and SET LONG defaults to 80 in SQLPlus, thus it will only show the first 80 characters of the expression unless you SET LONG to a higher value.
    Hemant K Chitale

  • Using Column Name in a Second Table

    I have two tables in a sheet, Data and Report. Data contains a column named Hours. How can I write a sum function in the Report table that sums the values in the Hours column in Data? I'd like to use a named reference instead of a row/column letter/number range for when the Hours column gets longer.

    David Benman1 wrote:
    Thanks. I tried what you said, but initially it didn't work. I realized I needed to make the top row a header row, but that leads to a new question. All my columns now can be reference by name except the first column. Is there anything special I need to do to the first column? If the first column is "Hours", then when I type in "Hours" in my formula, the spreadsheet doesn't recognize it as a column name.
    Yes, you must read the User Guide which explains :
    Yvan KOENIG (VALLAURIS, France) 2 septembre 2010 12:06:03

  • Using function in select statement

    Hi,
    CREATE FUNCTION [dbo].[udf_testFunction] 
    @value int
    RETURNS int
    AS
    BEGIN
    -- Declare the return variable here
    declare @returnValue int
    set @returnValue = @value*2;
    return @returnValue;
    END
    GO
    create table #Temp
        EmpID int, 
        EmpName Varchar(50)
    insert into #Temp(EmpID,EmpName) values(1,'Name1');
    insert into #Temp(EmpID,EmpName) values(2,'Name2');
    insert into #Temp(EmpID,EmpName) values(3,'Name3');
    insert into #Temp(EmpID,EmpName) values(4,'Name4');
    insert into #Temp(EmpID,EmpName) values(5,'Name5');
    select EmpID,EmpName, [dbo].[udf_testFunction](EmpID), [dbo].[udf_testFunction](EmpID)*EmpID,[dbo].[udf_testFunction](EmpID)+2 from #Temp
    In the above select statement i used [dbo].[udf_testFunction]() function 3 times. But i want to use only once and reuse it.
    Something like 
    select EmpID,EmpName, testfunctionvalue,testfunctionvalue*EmpID,testfunctionvalue+2 from #Temp
    Please advise me.... Thanks in Advance...

    You can use this code: 
    WITH cte
    AS ( SELECT EmpID ,
    EmpName ,
    [dbo].[udf_testFunction](EmpID) AS testfunctionvalue
    FROM #Temp
    SELECT EmpID ,
    EmpName ,
    testfunctionvalue ,
    testfunctionvalue * EmpID ,
    testfunctionvalue + 2
    FROM cte
    But using scalar functions in select clause can hurt the performance. Please see this link: 
    SQL Server Scalar User Defined Function Performance
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • How to use column name from subquery result set.

    I have these 2 tables
    SQL> select * from temp
      2  ;
    TABLE_NAME                     COLUMN_NAME                    TYPE
    lst                            name                           STATUS
    lst                            val
    SQL> select * from lst;
    TYPE                           NAME
      VAL
    STATUS                         Pending
      Pendiente
    STATUS                         Closed
      Cerrado
    STATUS                         ABC
      ABSI want to select column_name from temp table and generate select statements.
    select name from lst;
    select (select COLUMN_NAME from temp where rownum<2) from lst;
    SQL> select (select COLUMN_NAME from temp where rownum<2) from lst;
    (SELECTCOLUMN_NAMEFROMTEMPWHER
    name
    name
    nameoutput I expect is
    SQL> select name from lst;
    NAME
    Pending
    Closed
    ABC

    MichaelS wrote:
    Can I do it using SQLe.g.:)
    I was just about to post a similar approach (which should work from 10.2 and upwards) :
    SQL> SELECT value(x).getRootElement() col_name,
      2         extractvalue(value(x),'*') col_value
      3  FROM ( SELECT column_name, table_name
      4         FROM temp
      5         WHERE rownum = 1
      6       ) v
      7     , XMLTable(
      8        '/ROWSET/ROW/*'
      9        passing dbms_xmlgen.getXMLType('SELECT '||v.column_name||' FROM '||v.table_name)
    10       ) x
    11  ;
    COL_NAME        COL_VALUE
    NAME            Pending
    NAME            Closed
    NAME            ABC

Maybe you are looking for

  • Open Directory Server "not responding"

    This is strange, and I'm not sure what if anything is wrong... My server is an OD Master. LDAP, Password Server, and Kerberos all report running. AFP authentication is set to Kerberos (only). Authenticated directory binding is enabled. Client compute

  • Is there a way to open a browser and it "starts" with opening many tabs?

    Is there a way to open a browser and it "starts" with opening many tabs? e.g. I open a browser - and it starts on 3 or 4 tabs?

  • Something wrong with connectors on top of iPOD

    This is a strange one. I have a 60GB iPOD photo. One day my iTRIP stops working. The light and everyhting still work but no radio connection. So I assume that the iTRIP craped out. So I buy a new one same problem. So I thinksomething is wrong with th

  • Help needed with MMAPI and print values to screen

    Hi, Using the RingToneConverter, I want to print out the values to the screen that the ring tone has. The values I want printed are actually any values at all! I am not picky at this point! Can anyone help with this? I would like it so that while the

  • Error during DG data distribution

    Hi SAP DG Experts, I am configuring and testing DG data distribution from central EHS system to multiple ERP systems. I am able to send the DG idoc and ERP system is receiving that. But the DG data creation is failing and when I check DGp7 I can get