Concat to retrieve column name in select

This is basically what I am trying to do:
SELECT 'LY_'| |to_char(sysdate,'MON')| |'SALES' FROM TERR_ACCT_SUM
Except, instead of returning "LY_OCTSALES", I would like to select the rows in the column LY_OCTSALES. How can I "create" the column name to select?

Not sure if your question was meant using SQL*PLUS or java code.
If you want to use JDBC you could create SQL statements in a String variable and pass it to the executeQuery() method in the Statement object .
If you are using BC4J if you want you could create Dynamic View Objects based on SQL statments created at the run time.
raghu

Similar Messages

  • Retrieve column names of a table!!

    Hi all,
    I want to retrieve column names of a table 'test' whose values are null
    For ex:
    select * from test
    will give the results as
    column_1 column_2 column_3 column_4
    111
    lets consider the case that the table has only one record.
    accordingly we have to get column_2 ,column_3 and column_4 as the result.
    i tried dynamic 'execute immediate' statement and tried to extract in one single execute immediate statement but i was not able to accomplish because of the multiple columns.
    is it possible without using a pl/sql function or procedure??

    Check this:
    SQL> INSERT INTO my_Test values('ABCD',NULL,NULL);
    1 row created.
    SQL> COMMIT;
    Commit complete.
    SQL> select * from my_Test;
    COL1       C COL3
    ABCD
    SQL> declare
      2  CURSOR C1 IS SELECT column_name FROM all_tab_cols WHERE table_name = 'MY_TEST';
      3  v_sql VARCHAR2(10000) := NULL;
      4  my_null_col_list VARCHAR2(32767) := NULL;
      5  my_cnt NUMBER := 0;
      6  BEGIN
      7  FOR I in C1 LOOP
      8  v_sql := 'SELECT COUNT(*) FROM my_test WHERE '||I.column_name ||' IS NULL';
      9  execute immediate v_sql INTO my_cnt;
    10  IF (my_cnt > 0) THEN
    11  my_null_col_list := my_null_Col_list||','||I.column_name;
    12  END IF;
    13  END LOOP;
    14  my_null_col_list := SUBSTR(my_null_col_list,2);
    15  dbms_output.put_line('Columns that have null values for table my_Test are:'||my_null_col_list);
    16  END;
    17  /
    Columns that have null values for table my_Test are:COL2,COL3
    PL/SQL procedure successfully completed.
    SQL> desc my_test;
    Name                                      Null?    Type
    COL1                                               VARCHAR2(10)
    COL2                                               VARCHAR2(1)
    COL3                                               VARCHAR2(10)
    SQL>

  • Item value as column name in select

    Hi,
    I have a problem with selecting the columns in the query using items. For example: I have a query:
    select column_a from table; or select column_b from table;
    and I want to do something like this:
    - any item in which I choose the column name
    - query: select column_from_item from tale
    Is it possible?
    My apex version: 4.0.2.00.07
    My oracle db version: oracle 11g

    Unfortunately, it does not work. For example:
    I have a table book (title, themes ...), which is eight rows. When I create a static list of items containing the column names (display name and returns the name) and a report based on select according to your design(select :P5_select from table;), you get eight records in the name of the column.
    item: select list -> static list -> display value: Title, return value: Title, name: P1_title
    select :P1_title from books;
    result which i get:
    Title
    Title
    Title
    Title

  • How to remove column name in select clause

    Hello Guys,
    I just want to remove a column name in select clause. Because, I don't want to write all column names. I hope I express myself.
    In other words, I want the following.
    Select   * - unwanted_column  from table;
    instead of this
    Select col1, col2, col3, col4, ........ col 10000 from table;

    Hi,
    Sorry, there's nothing in SQL that means "all columns *except* ...". As the others have said, the only way to get those results in SQL is to list all the columns you do want.
    Your front end may have some feature that allows you to hide a specific column. For example, in SQL*Plus, you can use <tt> COLUMN ... NOPRINT </tt> , like this:
    COLUMN      dname     NOPRINT
    SELECT       *
    FROM       scott.dept
    ORDER BY  dname
    ;Output:
    `   DEPTNO LOC
            10 NEW YORK
            40 BOSTON
            20 DALLAS
            30 CHICAGOThere is a column called dname in the scott.dept table; the query above actually uses it. But, because of the COLUMN command, SQL*Plus won't display that column.
    Edited by: Frank Kulash on Feb 26, 2013 10:10 AM
    Changed scott.dept example.

  • Change column names when selecting from a collection

    Anyone know how to change C001,C002...etc to readable column names when selecting from a collection? Aliases don't work!
    Paul Platt

    Paul,
    Edit the report attributes and change the column headings by selecting the "Custom" radio button first.
    Sergio

  • Using PL/SQL to retrieve column names and column values

    If I have a table as follows
    Table A(
    meal varchar2(32),
    beverage varchar2(32),
    desert varchar2(32));
    and the table contains a row
    meal beverage desert
    pork chops iced tea apple crisp
    Is there a way in pl/sql to retrieve the column names along with the values. I have an object type
    DATA_DEFINITION_T AS OBJECT (
              "FIELD_NAME"          VARCHAR2(32),
              "FIELD_VALUE" VARCHAR2(32)
    I need to store the column name in field_name and the column value in field_value.
    So the result would be:
    FIELD_NAME = meal
    FIELD_VALUE = pork_chops
    FIELD_NAME = beverage
    FIELD_VALUE = iced tea
    FIELD_NAME = desert
    FIELD_VALUE = apple crisp
    Thanks in advance.

    Hi,
    try this procedure ....just create it and give the table name..the object M_DATA_TAB has the required data
    procedure l_fill_data_dict(p_table_name varchar2) is
    connection_id EXEC_SQL.CONNTYPE;
    bIsConnected BOOLEAN;
    cursorID EXEC_SQL.CURSTYPE;
    nIgn PLS_INTEGER;
    m_val VARCHAR2(40);
    m_col_name varchar2(40);
    m_col_val varchar2(240);
    m_cnt number;
    m_id number := 0;
    m_incr number := 0;
    p_sqlstr varchar2(4000);
    p_sql_cnt varchar2(4000) ;
    p_org_sql varchar2(4000);
    TYPE DATA_DEFINITION_TABS IS RECORD (
    FIELD_NAME VARCHAR2(32),
    FIELD_VALUE VARCHAR2(240));
    TYPE DATA_DEFINITION_TAB IS TABLE OF DATA_DEFINITION_TABS;
    M_DATA_TAB DATA_DEFINITION_TAB := DATA_DEFINITION_TAB();
    --m_file text_io.file_type;
    Begin
    --     m_file := text_io.fopen('c:\eg.txt','w');
         --Set default connection
    connection_id := EXEC_SQL.DEFAULT_CONNECTION;
    bIsConnected := EXEC_SQL.IS_CONNECTED;
    IF bIsConnected = FALSE THEN
         message('Connection Failed');
    RETURN;
    END IF;
    --Find the total no.of columns in the given table
    p_sql_cnt := 'Select COUNT(column_name) from user_tab_columns where table_name='''||p_table_name||''' order by column_id';
    cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_sql_cnt, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_val,40);
    nIgn := EXEC_SQL.EXECUTE(cursorID);
    IF (EXEC_SQL.FETCH_ROWS(cursorID) > 0) THEN
         EXEC_SQL.COLUMN_VALUE(cursorID, 1, m_val);
    end if;
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    --EXEC_SQL.CLOSE_CONNECTION;
    m_cnt := m_val;---column count
    ---get the column names from the user_Tab_columns and fetch the values from the given table for that column...
    For i in 1..m_cnt loop
         m_id := m_id+1;
    p_sqlstr := 'Select column_name from user_tab_columns where table_name='''||p_table_name||''' and column_id ='||m_id||' order by column_id';
    cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_sqlstr, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_col_name,40);
    nIgn := EXEC_SQL.EXECUTE(cursorID);
    IF (EXEC_SQL.FETCH_ROWS(cursorID) > 0) THEN
         EXEC_SQL.COLUMN_VALUE(cursorID, 1, m_col_name);
    end if;
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    --fetch the column value from the given table
         p_org_sql := 'select DISTINCT '||m_col_name||' from '||p_table_name;
         cursorID := EXEC_SQL.OPEN_CURSOR;
    EXEC_SQL.PARSE(cursorID, p_org_sql, exec_sql.V7);
    EXEC_SQL.DEFINE_COLUMN(cursorID, 1, m_col_val,240);
         nIgn := EXEC_SQL.EXECUTE(cursorID);
         Loop      
         nIgn := EXEC_SQL.FETCH_ROWS(cursorID);
              IF (nIgn > 0) THEN
                   EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 1, m_col_val);
    M_DATA_TAB.extend();
                   M_DATA_TAB(M_DATA_TAB.last).field_name := m_col_name;
                   M_DATA_TAB(M_DATA_TAB.last).FIELD_VALUE := m_col_val;
                   m_incr := m_incr+1;
                   -- text_io.put_line(m_file,m_col_name||'##'||m_col_val);
              else
                   exit;
              End if;
         End loop;--loop of records in the table for the given column
    EXEC_SQL.CLOSE_CURSOR(cursorID);
    End loop; ---loop of columns in the table
    --text_io.fclose(m_file);
    message('Total no. of items in the object='||m_incr);
    EXEC_SQL.CLOSE_CONNECTION;
    EXCEPTION
    When EXEC_SQL.Invalid_Connection then
         message('invalid connection');
         when EXEC_SQL.Package_Error     then
         message('pkg err');
         when EXEC_SQL.Invalid_Column_Number          then
         message('invalid col num defined');
         when others then
              MESSAGE(SQLERRM);
    End;
    Regards
    Dora
    Edited by: Dora on Sep 27, 2009 3:13 PM

  • How to retrieve column names in a query in a case sensitive way

    Given a query, I want to extract all the column names/aliases in the query in a case-sensitive way.
    When I use dbms_sql.describe_columns() or java.sql.ResultSetMetaData classes getColumnName() or getColumnLabel()
    it returns the columns name ONLY in Upper case.
    My application needs to extract the column names in the same case as it appears in the query string.
    Is there any API to get this without parsing the SQL query string?
    Thanks
    PS: The dbms_sql.describe_columns() returns the column name in upper case.
    declare
    IS
    l_column_recs DBMS_SQL.DESC_TAB;
    l_cur NUMBER;
    l_column_count NUMBER;
    BEGIN
    l_cur := dbms_sql.open_cursor;
    dbms_sql.parse(l_cur, 'select target_type from targets', dbms_sql.NATIVE);
    dbms_sql.describe_columns(l_cur, l_column_count, l_column_recs);
    FOR i IN l_column_recs.FIRST..l_column_recs.LAST
    LOOP
    dbms_output.put_line(l_column_recs(i).col_name);
    end loop;
    end;
    /

    As far as the result set is concerned, though, the column name is in all upper case. If you query the data dictionary, you would see that the TARGET_TYPE column in the TARGETS table is stored in upper case.
    The way Oracle works is that column names that are not enclosed in double-quotes are converted to upper case in the data dictionary and elsewhere and then Oracle looks for the column name in the table definition. That is what allows Oracle to have case-insensitive identifiers unless a user specifies case-sensitive identifiers by enclosing the identifier in double quotes.
    If you changed the query to be
    SELECT target_type as "target_type"
      FROM targetsOracle should report the alias in a case sensitive fashion because you've now indicated that the alias should be treated as case sensitive.
    Justin

  • ORA-00904: invalid column name in select query by using abstract datatype

    Hi,
    I had created abstract datatype as PERSON_TY and ADDRESS_TY ,
    after inserting the record . i'm tryng to select the column but i got the error , even i refferd all those thing. they are given that same please look this finde me a result.
    SQL> DESC PERSON_TY
    Name Null? Type
    NAME VARCHAR2(25)
    ADDRESS ADDRESS_TY
    SQL> DESC ADDRESS_TY
    Name Null? Type
    STREET VARCHAR2(30)
    CITY VARCHAR2(25)
    STATE CHAR(2)
    COUNTRY VARCHAR2(15)
    SQL> SELECT * FROM EMPLOYE
    2 ;
    EMP_CODE
    PERSON(NAME, ADDRESS(STREET, CITY, STATE, COUNTRY))
    10
    PERSON_TY('VENKAT', ADDRESS_TY('112: BLUE MOUNT', 'CHENNAI', 'TN', 'INDIA'))
    20
    PERSON_TY('SRINI', ADDRESS_TY('144: GREEN GARDEN', 'THAMBARAM', 'TN', 'INDIA'))
    SQL> SELECT PERSON.NAME FROM EMPLOYE
    2 ;
    SELECT PERSON.NAME FROM EMPLOYE
    ERROR at line 1:
    ORA-00904: invalid column name
    regards
    venki

    SELECT PERSON.NAME FROM EMPLOYEIf you look in the documentation, you will see that we need to alias the table in order to make this work:
    select e.person.name from employees e
    /Cheers, APC
    Blog : http://radiofreetooting.blogspot.com

  • Invalid Column Name on select from materialized view?

    Hey all, I have created this materialized view for my java to select from. For some reason when I try to select from it, I get invalid column name. Here is my mat view statement in its simplest form:
    create materialized view mv_pgridtcevcluster_property as
    select distinct clustername_ as "OBJECT_ID", CLUSTERNAME_, LICENSEMODE_
    from p_gridtcevcluster p
    order by clustername_;
    Now when I run my select statement from jdbc:
    SQL: select object_id from MV_PGRIDTCEVCLUSTER_PROPERTY
    java.sql.SQLException: Invalid column name
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
         at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3319)
         at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:1926)
         at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:1515)
         at com.mchange.v2.c3p0.impl.NewProxyResultSet.getString(NewProxyResultSet.java:3342)
         at historian.objects.mgmt.udrManagerTest.gatherObjects(udrManagerTest.java:73)
    Anyone have issues with this before? It seems to throw the error sporatically, any help would be much appreciated!
    Regards,
    TimS
    Edited by: TimS on Mar 30, 2009 1:54 PM
    Nevermind, figured it out. Was using wrong column name identifier when picking values from resultset.

    Since you have "OBJECT_ID" in quotes, Oracle stores the column name literally and case sensitively, and the column name must be capitalized when referenced.
    From a regular sql*plus window, try
    select object_id from mv_pgridtcevcluster_property;
    select OBJECT_ID from mv_pgridtcevcluster_property;
    select "OBJECT_ID" from mv_pgridtcevcluster_property;What is the result from each of them?

  • Dynamic column name with SELECT INTO

    I am trying to build a function that derives a pay amount from a set of business rules. There are about 40 columns that hold various pay amounts and their column names are variations of 4 indicators (day shift, vs night shift, etc.) that I have to dynamically look up, ie here is the ID number and a timecard, now figure out which of the 40 fields to look up to get the pay amount.
    I can determine from the timecard and employee ID which field to look at, but I'm getting hung up with the syntax needed to construct and execute the statement inside the PL/SQL block. I need to RETURN the pay I extract using the function, and I can create the correct SQL statement, but the EXECUTE IMMEDIATE won't accept the SELECT INTO syntax.
    Can someone please suggest a solution? Here is the function:
    create or replace FUNCTION FN_GET_PAYRATE(tc in NUMBER, e in NUMBER, pc in VARCHAR2)
    RETURN NUMBER
    IS
    e_id NUMBER;
    tc_id NUMBER;
    pl_cd VARCHAR2(7);
    shft VARCHAR2(2);
    lvl VARCHAR2(2);
    typ VARCHAR2(2);
    e_typ VARCHAR2(4);
    proj NUMBER;
    hrly VARCHAR2(4);
    payrt NUMBER;
    var_col VARCHAR2(10);
    sql_select VARCHAR2(200);
    sql_from VARCHAR2(200);
    sql_where VARCHAR2(200);
    sql_and1 VARCHAR2(200);
    sql_and2 VARCHAR2(200);
    sql_and3 VARCHAR2(200);
    sql_orderby VARCHAR2(200);
    var_sql VARCHAR2(2000);
    BEGIN
    e_id := e;
    tc_id := tc;
    pl_cd := pc;
    SELECT NVL(SHIFT,'D') INTO shft
    FROM TS_TIMECARD_MAIN
    WHERE TIMECARD_ID = tc_id;
    --DBMS_OUTPUT.PUT_LINE('SHIFT= ' || shft);
    SELECT NVL(PAY_LVL, 1), NVL(PAY_TYPE, 'B'), NVL(RTRIM(EMP_TYPE), 'LHD'), NVL(PROJECT, 001)
    INTO lvl, typ, e_typ, proj
    FROM TS_EMPLOYEES
    WHERE EMP_ID = e_id;
    --DBMS_OUTPUT.PUT_LINE('Level= ' || lvl);
    --DBMS_OUTPUT.PUT_LINE('PAY_TYPE= ' || typ);
    --DBMS_OUTPUT.PUT_LINE('EMP_TYPE= ' || e_typ);
    --DBMS_OUTPUT.PUT_LINE('PROJECT= ' || proj);
    IF e_typ <> 'LHD' THEN
    hrly := 'H';
    ELSE
    hrly := '';
    END IF;
    IF proj <> 001 THEN
    var_col := shft || lvl || typ || hrly;
    --DBMS_OUTPUT.PUT_LINE('RATE COLUMN= ' || var_col);
    sql_select := 'SELECT NVL(' || var_col || ', .01) INTO payrt';
    sql_from := ' FROM TS_PAYRATES';
    sql_where := ' WHERE PROJECT_ID = ' || proj;
    sql_and1 := ' AND ACTIVE = 1';
    sql_and2 := ' AND JOB_TYPE = ' || CHR(39) || e_typ || CHR(39);
    sql_and3 := ' AND PILE_ID = ' || CHR(39) || pl_cd || CHR(39);
    var_sql := sql_select || sql_from || sql_where || sql_and1 || sql_and2 || sql_and3 || sql_orderby;
    DBMS_OUTPUT.PUT_LINE('SQL: ' || var_sql);
    EXECUTE IMMEDIATE var_sql;
    DBMS_OUTPUT.PUT_LINE('RATE= ' || payrt);
    RETURN payrt;
    ELSE
    DBMS_OUTPUT.PUT_LINE('ERROR');
    RETURN 1;
    END IF;
    END;
    I have alternately tried this:
    SELECT NVL(var_col,.01) into payrt
    FROM TS_PAYRATES
    WHERE PROJECT_ID = proj AND ACTIVE = 1
    AND JOB_TYPE = CHR(39) || e_typ || CHR(39)
    AND PILE_ID = CHR(39) || pl_cd || CHR(39);
    as a substitute for the EXECUTE IMMEDIATE block, but I can't seem to use a dynamic substitution for the column name.
    Any help would be greatly appreciated.

    That's the most difficult part - the error messages seem to indicate a problem with the SQL statement in its execution context, because I can take the SQL string by itself and it executes perfectly.
    Here are three variations:
    SELECT INTO
    select fn_get_payrate(21555, 30162, 15) from dual
    ERROR at line 1:
    ORA-00905: missing keyword
    ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 60
    SQL: SELECT NVL(N4P , .01) INTO payrt FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
    Without SELECT INTO  (returns NULL)
    SQL> select fn_get_payrate(21555, 30162, 15) from dual;
    FN_GET_PAYRATE(21555,30162,15)
    SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
    RATE=
    EXECUTE IMMEDIATE USING
    SQL> select fn_get_payrate(21555, 30162, 15) from dual;
    select fn_get_payrate(21555, 30162, 15) from dual
    ERROR at line 1:
    ORA-01006: bind variable does not exist
    ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 61
    SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'

  • How to retrieve column name from Excel using POI HSSF eventusermodel?

    Hi ,
    I am simply reading the excel sheet and writing in a txt file. I have done the following in the switch construct. It works fine but I want to retrieve only the column header. But this code gives me all available strings in the excel sheet. Any pointer would be greatly appreciated.
    case SSTRecord sid : 
             SSTRecord sstrecord = (SSTRecord) record;
             for (int i=0; i<sstrecord.getNumUniqueStrings(); i++){      
                  System.out.println(" Column name" +  sstrecord.getString(i));
    break;bye for now
    Sat

    try labels:
            case LabelSSTRecord.sid:
                LabelSSTRecord lrec = (LabelSSTRecord) record;
                if (lrec.getRow() == 0) {
                    System.out.println(" Column name "
                            + sstrec.getString(lrec.getSSTIndex()));
                break;

  • Passing parameters to table valued functions and using parameters as column name on select

    I am creating a function where I want to pass it parameters and then use those parameters in a select statement. When I do that it selects the variable name as a literal not a column. How do I switch that context.
    Query:
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
    @BANNER_COLUMN AS VARCHAR(MAX),
    @ORION_COLUMN AS VARCHAR(MAX)
    RETURNS @Banner_Orion_Employee_Comparison TABLE 
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison
    (LAST_NAME, BANNER, ORION)
    SELECT
    a.LAST_NAME, @BANNER_COLUMN, @ORION_COLUMN
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    Output
    I execute this:
    select * from ufn_Banner_Orion_Employee_Comparison_parser_v2 ('a.BANNER_RANK' , 'b.[rank]')
    and get:
    Cerecerez NULL
    NULL a.BANNER_RANK
    b.[rank]
          

    George,
    You could go for using a CASE statement as earlier mentioned by Erland. This would look like below: (Downside is that you need to be mentioning all possible values in the CASE)
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
    @BANNER_COLUMN AS VARCHAR(MAX),
    @ORION_COLUMN AS VARCHAR(MAX)
    RETURNS @Banner_Orion_Employee_Comparison TABLE
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
    SELECT
    a.LAST_NAME
    , CASE @BANNER_COLUMN WHEN 'a.BANNER_RANK' THEN a.BANNER_RANK WHEN 'a.BADGE' THEN a.BADGE END --put values as required
    , CASE @ORION_COLUMN WHEN 'b.[rank]' THEN b.[rank] END --put values as required
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    Another method that I would suggest is to get all values from the function, then build a dynamic query to obtain results from it .. Something like:
    ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]()
    RETURNS @Banner_Orion_Employee_Comparison TABLE
    LAST_NAME nvarchar(max),
    EMPNO int,
    BannerColumnName nvarchar(max),
    BANNER nvarchar(max),
    ORION nvarchar(max)
    AS
    BEGIN
    INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
    SELECT
    * --Returns all the columns
    FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
    inner join IWM_Stage.dbo.ViewPersonnel AS b
    on a.BADGE = b.badge
    WHERE a.EMP_STATUS = 'A'
    and a.BANNER_RANK <> b.[rank]
    RETURN;
    END;
    GO
    --Execution
    DECLARE @BANNER_COLUMN AS VARCHAR(MAX), @ORION_COLUMN AS VARCHAR(MAX),@SQL NVARCHAR(MAX)
    SET @BANNER_COLUMN='BANNER_RANK'
    SET @ORION_COLUMN='[rank]'
    SET @SQL='
    select LAST_NAME,'+@BANNER_COLUMN+','+@ORION_COLUMN+' from ufn_Banner_Orion_Employee_Comparison_parser_v2 ()'
    PRINT @SQL
    EXEC @SQL
    You just need to make sure that the column names returned by the function are UNIQUE (Using proper alias names) so that you don't have a problem referring to them from the outside..
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Retrieving Column Names from a Query

    I need to be able to generate XML that looks like this:
    <Categories>
    <Category Name='Arrivals'/>
    <Category Name='Departures'/>
    <Category Name='Unused'/>
    <Category Name='Out of Commission'/>
    </Categories>
    Where the name attribute value is the name of columns in a query. For example, a standard SQL query might look something like this:
    select
    year, arrivals, departures, unused, out_of_commission
    from
    some_table
    I am able to generate the XML that represents the data just fine. However, my vended application is requiring this column header information. I've browsed and searched the XMLDB documentation but could not see a way to retrive the column names returned by the query. I think I Just need to be pointed in the right direction.
    Thanks,
    Steve

    What technique are you itending using to generate the XML ?.
    Does something like this work
    select xmlelement("Categories",
    xmlelement("Category", xmlattributes('Arrivals' as "Name"), Arrivals),
    xmlelement("Category", xmlattributes('Departures' as "Name"), Departures),
    xmlelement("Category", xmlattributes('Unused' as "Name"), Unsused),
    xmlelement("Category", xmlattributes('Out Of Commission' as "Name"), Out_of_Commission)
    from some_table

  • Cannot use alias for dynamic column name in SELECT statement

    Hi,
    I want to retrieve values from several tables by using dynamic column & table name as below:
    DATA: tbl_name(30) TYPE c VALUE '/bic/tbi_srcsys',  " staticly initialized for this example
               col_name(30) TYPE c VALUE '/bic/bi_srcsys'.  " staticly initialized for this example
    SELECT (col_name) INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    The internal table "it_values" does not contain a field named "/bic/bi_srcsys", instead it has another generic field "value" so that the above code can be applied to other tables. I tried to use alias (AS) as below:
    SELECT (col_name) AS value INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    But this cannot work. I know that there are other ways to solve this problem, such as by using a single field in SELECT .. ENDSELECT and subsequently appending it to the work area and internal table as below:
    SELECT (col_name)  INTO (lv_value) FROM (tbl_name).
      wa_value-value = lv_value.
      APPEND wa_value TO it_values.
    ENDSELECT.
    Just wonder if there is any other more elegant workaround, because I might have several other fields instead of only one?
    Thanks.
    Regards,
    Joon Meng

    Hi Suhas,
    thanks for the quick reply.
    Sorry that I have not well described the structure of the internal table "it_values". This internal table contains several other fields (key, type, value, etc.).
    I guess that the following code
    SELECT (col_name) INTO TABLE it_values FROM (tbl_name).
    works if the internal table only has one field (value) or the field "value" is in the first position, right?
    In this case, I need to fill the "value" field of internal table it_values (ignore the other fields like type, key) with values retrieved from (col_name) of the DDIC table.
    Looking forward to your reply.
    BR,
    Joon Meng

  • Selecting from a SQL Server 2005 with long column names ( 30 chars)

    Hi,
    I was able to set up a db link from Oracle 11.2.0.1 to SQL Server 2005 using DG4ODBC.
    My problem is that some column names in the Sql Server are longer than 30 chars and trying to select them gives me the ORA-00972: identifier is too long error.
    If I omit these columns the select succeeds.
    I know I can create a view in the sql server and query it instead of the original table, but I was wondering if there's a way to overcome it with sql.
    My select looks like this:
    select "good_column_name" from sometable@sqlserver_dblink -- this works
    select "good_column_name","very_long_column_name>30 chars" from sometable@sqlserver_dblink -- ORA-00972Thanks

    I tried creating a view with shorter column names but selecting from the view still returns an error.
    create view v_Boards as (select [9650_BoardId] as BoardId, [9651_BoardType] as BoardType, [9652_HardwareVendor] as
    HardwareVendor, [9653_BoardVersion] as BoardVersion, [9654_BoardName] as BoardName, [9655_BoardDescription] as BoardDescription,
    [9656_SlotNumber] as SlotNumber, [9670_SegmentId] as SegmentId, [MasterID] as MasterID, [9657_BoardHostName] as BoardHostName,
    [9658_BoardManagementUsername] as BoardManagementUsername, [9659_BoardManagementPassword] as BoardManagementPassword,
    [9660_BoardManagementVirtualAddress] as BoardManagementVirtualAddress, [9661_BoardManagementTelnetLoginPrompt] as
    MANAGEMENTTELNETLOGINPROMPT, [9662_BoardManagementTelnetPasswordPrompt] as MANAGEMENTTELNETPASSPROMPT,
    [9663_BoardManagementTelnetCommandPrompt] as MANAGEMENTTELNETCOMMANDPROMPT FROM Boards)performing a select * from this view in sqlserver works and show the short column names
    this is the error i'm getting for performing a select * from v_boards@sqlserver_dblink
    ORA-28500: connection from ORACLE to a non-Oracle system returned this message:
    [Microsoft][SQL Native Client][SQL Server]Invalid column name 'BoardManagementTelnetLoginProm'. {42S22,NativeErr = 207}[Microsoft]
    [SQL Native Client][SQL Server]Invalid column name 'BoardManagementTelnetPasswordP'. {42S22,NativeErr = 207}[Microsoft][SQL Native
    Client][SQL Server]Invalid column name 'BoardManagementTelnetCommandPr'. {42S22,NativeErr = 207}[Microsoft][SQL Native Client][SQL
    Server]Statement(s) could not be prepared. {42000,NativeErr = 8180}
    ORA-02063: preceding 2 lines from sqlserver_dblinkI also tried replacing the * with specific column names but it fails on the columns that have a long name (it doesn't recognize the short names from the view)
    what am I doing wrong?
    Edited by: Pyrocks on Dec 22, 2010 3:58 PM

Maybe you are looking for