Extraction of values based on column names

Hello

I have three tables. Table A table contains a column with all column_names in the table b. table B is to have an emp_id and other fields that are stored as values in the column of the TABLE.  I need to get the emp_id and value from the column of table B based on data of Table A. and store it in another table.

Example:

Table has -col1

Emp_name

Emp_sal

Emp_dept

Table B

Emp_id Emp_name Emp_sal Emp_dept

1001 ABC 1000 sales

1002 XYZ 2000 SVC

TABLE C

Emp_id Emp_details value

1001 Emp_name ABC

1001 Emp_sal 1000

1001 Emp_dept sales

1002 Emp_name XYZ

1002 Emp_sal 2000

1002 Emp_dept SVC

Using the list of TABLE A, I have to select each Id and corresponding to the value of TABLE B and even insert in TABLE C. I know that we can use a loop for, but I have trouble choosing the name of column based on the value of the slider. Can anyone help?


Hello

Looks like you want to do 2 things rather difficult:

(1) unpivot data from several columns in the column 1 value

(2) get the column names for the another table unpivot operator

Let's start with how you could do just part 1, unpivoting data:

INSERT INTO table_c (emp_id, emp_details, value)

WITH all_varchar2 AS

(

SELECT emp_id

emp_name

TO_CHAR (emp_sal) AS emp_sal

emp_dept

--Include all columns, you might need

OF table_b

)

SELECT emp_id, emp_details, value

Of all_varchar2

UNPIVOT (value

FOR emp_details IN

(emp_name - dynamic

emp_sal - dynamic

emp_dept - dynamic

)

)

;

Value is a column, everything happens in this column must have the same (or a very similar) data type.  The subquery all_varchar2 converts all columns that you can rotate in VARCHAR2s (if they are not already VARCHAR2s) so that they are ready to rotate.  You might consider doing a permanent display for this.

Now, instead of hard-Ghoshal the 3 line marked "Dynamics", you seek to table_a.  You will know beforehand what are these columns, and you won't even know there will be the number of columns. You need instructions SQL dynamic to write this part of the INSERT statement for you at run time.

Here's a way to do it in SQL * more and SQL:

-The preliminary motion

COLUMN col_list_col by col_list new_value

SELECT LISTAGG (col1, ',') within THE GROUP (ORDER BY col1)

AS col_list_col
FROM table_a;

-Main return (dynamic):

INSERT INTO table_c (emp_id, emp_details, value)
WITH all_varchar2 AS
(
SELECT emp_id
emp_name
TO_CHAR (emp_sal) AS emp_sal
emp_dept
--Include all columns, you might need
OF table_b
)
SELECT emp_id, emp_details, value
Of all_varchar2
UNPIVOT (value
FOR emp_details IN
(& col_list
)
)
;

Dynamic SQL often works like this.  First, you make a preliminary motion to write the part that is not know before execution.  Then, you run the main statement, which has the integrated preliminary query results.

If you do this in PL/SQL, you use a string variable ordinary for col_list, instead of a substitution variable.

Tags: Database

Similar Questions

  • ID - value in XML format. How to extract the value based on the id?

    Hello

    I have a XML type

    < root >
    < resource >
    < id > 123 / < ID >
    < value > CBA < / value >
    < / resource >
    < resource >
    < id > 456 / < ID >
    def < value > < / value >
    < / resource >
    < / root >

    It is stored in a column of XMLTYPE as a CLOB.

    Now, I want to get a particular value based on one id.

    I tried to use the following syntax

    ([Select case when existsnode(x.XML_CLOB,'/Root/Resource[Id="123"]') = 1
    then extractValue(x.XML_CLOB,'/Root/Resource/Value')

    but "/ Root / / value of resource" can mean either of the 2 values. How to solve this?

    Hello

    If the element 'id' is unique you just specify XPath to the 'value' on the basis of extractvalue (given that you are pregnant of a single node):

    WITH x AS (
     SELECT xmltype(
     '
     123abc
     456def
     '
     ) xml_clob
     FROM dual
    )
    SELECT extractvalue(x.xml_clob, 'root/resource[id="123"]/value')
    FROM x
    WHERE ...
    ;
    
  • How to extract the values of XMLTYPE column,

    SQL > create table temporary global xmtype_tab (xmlfile xmltype);

    SQL > select * from all_directories;

    SYS RESTOREDIR/home / / dbimptask /.

    insert into xmtype_tab values (xmltype (dbms_xslprocessor.read2clob ('RESTOREDIR ','LAS_SETUP.xml ')));

    1 line of creation.

    SQL > select * from xmtype_tab;

    XMLFILE
    --------------------------------------------------------------------------------
    <? XML version = "1.0"? >
    rowset <>
    < ROW >
    < DATA_CAPTURE_ON > 1 < / DATA_CAPTURE_ON >


    How to extract the values inside each tag?


    XML file has the following data...


    rowset <>
    < ROW >
    < DATA_CAPTURE_ON > 1 < / DATA_CAPTURE_ON >
    < > 9600 BAUD_RATE < / BAUD_RATE >
    < ACK_TIMEOUT > 1 < / ACK_TIMEOUT >
    < TUBE_TRAVEL_LIMIT > 4 < / TUBE_TRAVEL_LIMIT >
    < SEND_SID_TIMEOUT > 1 < / SEND_SID_TIMEOUT >
    < INDEX_Q_TIMEOUT > 2 < / INDEX_Q_TIMEOUT >
    < HW_HANDSHAKING > 1 < / HW_HANDSHAKING >
    < / ROW >
    < / LINES > ';

    I use the Oracle 10.2.0.3 version...

    Why does this work?

    You are missing the tag of the ROWSET:

    select extractvalue (xmlfile, '/ROWSET/ROW/BAUD_RATE') baud_rate
      from xmltype_tab
     where existsnode (xmlfile, '/ROWSET/ROW/BAUD_RATE') = 1;
    
  • Dependent on the value of query column names

    Hi guys, I don't think this is possible, but I thought I'd give it a go.

    I am wanting to values that are returned by my query as column headings. For example:

    SELECT 1,2,3,4,5
    OF trade_table
    WHERE < 6

    The table contains 10 records, "A1", "B1", "C1", "D1", "E1", "F1" etc... and my query returns 5 records of each with a rating of 1 to 5. The first record in the standings, lets say "D1" must be the column heading.

    I'm extremely sorry for being vague, but my request first contains a lot of analytical functions and I try to simplify it.

    Thanks in advance.

    To do this with the reporting you tool use and not with SQL and PL/SQL.

  • Read the value of XML or JSON based on the name of the key

    I can't figure out how to get the value of the url to Image_Calendar1 JSON or XML data.  Sorry if it's 'obvious', but I am a new developer.

    I was cheating and ListItemData.value [1] .url but in this case, that the XML feed changes the number values of the moments which throws out of my method.  I need to be able to get the value based on the name of the key.  Is this possible?

    Thank you. Examples of the XML and the JSON /port.

    Okay, it might not be pretty, but what I do to solve my problem is to convert the ListItemData in JSON and stringify it.  I then split the string with 'key' and then count the lines.  Would not work if 'key' wasn't in each line, or if there are child elements of the child elements.  But... it works for me at the moment.  Future, me I hope, will be more intelligent and can fix it when it breaks.

    var testString = String (JSON.stringify (ListItemData))

    var javascriptcount = String (testString.split("key").length - 1).

    Console.log ("try to use the length:" + javascriptcount)

  • Question PLSQL with variable compound column names

    Hello gentlemen,


    I'm new to PLSQL and I would like to display some values of columns, which are listed in the defined variable in dbms.output. I created under code, which I think it could work, but I guess that it is far from correct.


    DECLARE
    v_TEMP_QUERY VARCHAR2
    (1000 BYTE);
    v_TEMP_VALUE VARCHAR2
    (1000 BYTE) := 'FILTER_01, FILTER_02';

    BEGIN  
    FOR v_TEMP_LOOP IN
    (v_TEMP_QUERY := 'SELECT DISTINCT ' || v_TEMP_VALUE || ' FROM CW_PAGE_COMPONENT_TEMPL WHERE COMPONENT_TEMPL_ID = 10000034642';
    EXECUTE IMMEDIATE v_TEMP_QUERY; )
    LOOP
    DBMS_OUTPUT
    .PUT_LINE (v_TEMP_LOOP.v_TEMP_VALUE);
    END LOOP;
    END;


    Thanks in advance for your help and advice on this issue and sincerely,

    Sebastian

    OK, first of all, you're confused concepts here.

    cursor loop FOR waiting for a slider must be provided, and yet you offer an assignment statement and a command immediately execute for it.  Syntax is not valid.

    Secondly, you force the way of the use of dynamic SQL, which is generally bad practice.  This use of the SQL is rarely necessary, because it often indicates that functional requirements, database design, or design/code enforcement has not examined properly... the first question is "why don't you know the names of the columns to select.  With dynamic columns in your query, you need some kind of dynamic code to manage the results of the query, you will not be able to reference the columns directly by name.

    Thirdly, the DBMS_OUTPUT package doesn't make "blank".  This may sound pedantic, but it's a common mistake that people make.  There is no fill data dbms_output buffer.  It relies on call code/interface to read the contents of the output buffer and display it in fact (for example, in SQL * more you use SQL * Plus the command "set serveroutput we ' to achieve)

    In general, in a well designed where application you know your columns you would only make...

    Start
    I'm in (select distinct filter_01, filter_02 from vw_page_component_templ where component_templ_id = 10000034642)
    loop
    dbms_output.put_line (i.filter_01 | ',' | i.filter_o2);
    end loop;
    end;

    If the columns are dynamic, then you have three options:

    (1) create a ref and pass cursor who back, extracting the content for example

    sys_refcursor getRc function returns (in numbers, in colnames templ_id varchar2) is
    RC sys_refcursor;
    Start
    Open rc for ' select distinct ' | colnames |' from vw_page_component_templ where component_teml_id =: 1' using templ_id;
    return rc;
    end;

    In SQL * more:

    var r refcursor; -It creates a variable in SQL * Plus ref cursor type
    Start
    : r: = getRc (10000034642, ' filter_01, filter_02');
    end;
    /
    print r;      -It's SQL * command to retrieve the cursor open and display the results

    (2) create an object and collection of the right structure to receive the results and use execute immediate to select IN this structure.

    (I will not show in this way, because it is absolute rubbish, and if you know the columns that you want to create the object and the collection, then you should not use dynamic SQL in the first place)

    (3) use the DBMS_SQL package to run the query and retrieve the data from the column in position rather than example:

    create or replace procedure run_query (p_sql IN VARCHAR2) is
    v_v_val varchar2 (4000);
    number of v_n_val;
    date of v_d_val;
    number of v_ret;
    c number;
    number d;
    whole col_cnt;
    Boolean f;


    rec_tab dbms_sql.desc_tab;
    number of col_num;
    v_rowcount number: = 0;
    Start
    -create a slider
    c: = dbms_sql.open_cursor;
    -analyze the SQL statement in the cursor
    DBMS_SQL. Parse (c, p_sql, dbms_sql.native);
    -run the cursor
    d: = dbms_sql.execute (c);
    --
    -Describe the columns that are returned by the SQL statement
    DBMS_SQL. DESCRIBE_COLUMNS (c, col_cnt, rec_tab);
    --
    -Local variables Bind to return to the different columns according to their types
     
    dbms_output.put_line (' number of columns in the query: ' | col_cnt);
    1.col_cnt j
    loop
    case rec_tab (j) .col_type
    When 1 then dbms_sql.define_column (c, j, v_v_val, 2000); -Varchar2
    When 2 then dbms_sql.define_column (c, j, v_n_val);      -Number
    12. When can dbms_sql.define_column (c, j, v_d_val);     -Date
    on the other
    DBMS_SQL.define_column (c, j, v_v_val, 2000);  -Any other type of return as varchar2
    end case;
    end loop;
    --
    -Display columns are returned...
    dbms_output.put_line ('- Columns-');
    1.col_cnt j
    loop
    dbms_output.put_line (rec_tab (j) .col_name |') -' || case rec_tab (j) .col_type when 1 then 'VARCHAR2 '.
    When 2 then 'NUMBER '.
    When 12 can "DATE".
    "Otherwise, 'Other' end);
    end loop;
    dbms_output.put_line('---');
    --
    -This part generates the DATA
    loop
    -Retrieves a row of data using the cursor
    v_ret: = dbms_sql.fetch_rows (c);
    -Output when no more line
    When the output v_ret = 0;
    v_rowcount: = v_rowcount + 1;
    dbms_output.put_line (' line: ' | v_rowcount);
    dbms_output.put_line('---');
    -Extract the value of each column of the row
    1.col_cnt j
    loop
    -Fetch each column to the correct data type according to the description of the column
    case rec_tab (j) .col_type
    When 1 then dbms_sql.column_value (c, j, v_v_val);
    dbms_output.put_line (rec_tab (j) .col_name |': ' | v_v_val);
    When 2 then dbms_sql.column_value (c, j, v_n_val);
    dbms_output.put_line (rec_tab (j) .col_name |': ' | v_n_val);
    12. When can dbms_sql.column_value (c, j, v_d_val);
    dbms_output.put_line (rec_tab (j) .col_name |': ' | to_char (v_d_val,' DD/MM/YYYY HH24:MI:SS'));))
    on the other
    DBMS_SQL.column_value (c, j, v_v_val);
    dbms_output.put_line (rec_tab (j) .col_name |': ' | v_v_val);
    end case;
    end loop;
    dbms_output.put_line('---');
    end loop;
    --
    -Close the cursor, now we're done with it
    DBMS_SQL.close_cursor (c);
    END;
    /

    SQL > run_query exec ('select ename, empno, sal, deptno from emp where deptno = 10');
    Number of columns in the query: 4
    -Columns-
    EMPNO - NUMBER
    ENAME - VARCHAR2
    DEPTNO - NUMBER
    SAL - NUMBER
    -------------
    Line: 1
    --------------
    EMPNO: 7782
    ENAME: CLARK
    DEPTNO: 10
    SAL: 2450
    --------------
    Row: 2
    --------------
    EMPNO: 7839
    ENAME: KING
    DEPTNO: 10
    SAL: 5000
    --------------
    Row: 3
    --------------
    EMPNO: 7934
    ENAME: MILLER
    DEPTNO: 10
    SAL: 1300
    --------------

    PL/SQL procedure successfully completed.

    As you can see with this method, you can extract the column details, including the name and data etc. types and then extract each line and extract the data from the column position.

    Of course, this is quite complex, so it would be a last resort.

  • Extract specific values of XML (Oracle 11)

    Hello
    First of all... Please excuse my English... I'm Belgian ;)

    I have a 'Messages' table in Oracle 11, with a "xml_request" of type XMLTYPE field. Say that it contains the following data (sorry for the formatting, couldn't help it).

    <? XML version = "1.0" encoding = "UTF-8"? > <!-example XML file generated by XMLSpy v2008 rel. 2 sp2 (http://www.altova.com)-> < answer xsi: schemaLocation = "http://www.ept.lu/soa/2.0/Envelope Envelope_WSLF.xsd" xmlns = "http://www.ept.lu/soa/2.0/Envelope" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:pivot = "http://www.ept.lu/soa/2.0/Pivot" > < header > < senddt > 2010-12-17 T 09: 30:47.0Z < / senddt > < correlationid > 22222222 < / correlationid > < service > < type > WS - ATH < / type > < action > WS-ATH_ActivationSuccess < /. action > < / service > < source > < name > IOP < / name > < id > YYYYYYY < /ID > < / source > < destination > < name > OAO < / name > < id > XXXXXXX < /ID > < / destination > < authentication > < userid > USERID_OAO < / userid > < password > PASSWORD_OAO < / password > < / authentication > < / header > < body > < pivot : customer > < pivot: services > < pivot: service > < pivot: accessServiceId > 13100000000 < / pivot: accessServiceId > < pivot: serviceAttributes > < pivot: attribute > < pivot: name > BOOKING_MANAGER_ID < / pivot: name > < pivot: value > 12521515 < / pivot: value > < / pivot: attribute > < / pivot: serviceAttributes > < pivot: serviceAttributes > < pivot : attribute > < name: PivotTable > DEER < / pivot: name > < pivot: value > 1286001434 < / pivot: value > < / pivot: attribute > < / pivot: serviceAttributes > < / pivot: service > < / pivot: services > < / pivot: customer > < / body > < fault > < code > MI.006 < / code > < reason > success: ATH < / pattern > < failure / > < / answer >

    I'm trying to extract some values based on labels, for example I need to retrieve the value contained in the group with the name "DEER" in a query, in this case waiting for the query to return 1286001434.
    I quickly tried this, which returns nothing (which is not surprised, I guess that's completely wrong):

    Select EXTRACTVALUE (m.xml_request,'/response/body/client/services/service/serviceAttributes/value[@name="STAG"]','xmlns= "http://www.ept.lu/soa/2.0/Envelope") 'DEER '.
    Message m

    Thank you for your help.
  • [SOLVED] Property of the label of the box = MySQL column name

    Hello!
    I'm trying to get the value of a column in a MySQL database to link to the label of a checkbox property.
    I use a Repeater to retrieve all records in the database - but what I really need, but the names of column to a table and not the lines/records.

    So, is it possible to get the values of the column names in a MySQL via a PHP request directly, or I have to create a
    an XML file separate that contain manually entered values?

    Thanks for your help!
    Kind regards
    Christo

    This has been resolved.

    See the code below
    Kenwio

    THE FLEX AND PHP CODE:

  • questions to move a column name as parameter. Please advice.

    Hi all

    I have some difficulties with oracle reports. I am a novice with the beginner 2 days.
    I am not able to use the lexical settings in reports. my query is as easy as

    Select & column-name abc xyz;

    I tried to make a setting before creating the SQL but I always get the error saying that ORA-00922: lack of expression.
    also I tried with bind variables like

    Select: col_name abc xyz;

    but it gives a: inplace Column of records the data.

    some could help me with step by step procedure to create a lexical parameter.

    I am using reports 6i.

    Please let me know for details.

    Thanks in advance!

    Hello

    I suggest you create a sing an example 'Basic' of the EMP table: (see the demobld.sql script provided with Developer Suite to create this table)

    Create a new report
    Create a COLUMN name parameter:
    Name = COLNAME
    DataType = character
    Width = 20
    Initial value = ENAME

    Create a SQL query: select & emp colname

    Create a page layout manually or with the wizard

    Click on the button «Run paper Layout»

    Enter a valid value for the 'column' name (ENAME / JOB / SAL / COMM /...)

    Concerning

  • How to extract the values of column aliases based on different column values?

    Hello gurus,

    I have a table with the following struture-
    "drop table T;
    create table T(Name, Symbol, Amount,dep) as select
    'Anderia', 'AA', 1050000,'HR' from dual union all select
    'Michael', 'ML',150000,'Sales' from DUAL union all select
    'Bill', 'BL', 1050000,'Finance' from dual union all select
    'Nancy', 'NY', 4000,'HR' from DUAL union all select
    'Anderia', 'AA',3000,'HR' from dual union all select
    'Michael', 'ML',1050000,'Sales' from DUAL union all select
    'Bill', 'BL', 1200000,'Finance' from DUAL union all select
    'Anderia', 'AA', 1200000,'HR' from DUAL union all select
    'Vish', 'VH', 1200000,'Marketing' from DUAL;"
    And try to find the values of the column as
    Name, symbol, dep, amount, % Total, Total $Cumm, rank but some additional as-columns

    Amount HR, % HRTotal, $HR Cumm Total,
    Finance amount, FinanceTotal %, $Finance Cumm Total
    Sales amount, a percentage of Total sales, $Sales Cumm Total.
    Amount marketing, MarketingTotal %, $Marketing Cumm Total

    then I use the following query to retrieve the name, the symbol, the dep, amount, % Total, Total $Cumm, rank columns.
    select name
         , decode(grouping(symbol), 0, symbol, 'Total') symbol
         , dep
         , sum(amount) amount
         , sum(per_total) "% Total"
         , decode(grouping(symbol), 0, max(Cum_per_total), null) "% Cumm Total"
         , decode(grouping(symbol), 0, max(rank), null) rank
      from (
              select name
                   , symbol
                , dep
                   , amount
                   , per_total 
                   , sum(per_total) over(order by rk) cum_per_total
                   , rank
                   , rk
                from (     
                        select name
                             , symbol
                    , dep
                             , sum(amount) amount
                             , round((sum(amount)/max(total_amount)) * 100,2) per_total
                             , dense_rank () over (order by sum(amount) desc) as rank
                             , row_number() over(order by sum(amount) desc) as rk
                          from (
                                 select name
                                      , symbol
                                      , amount
                          , dep
                                      , sum(amount) over() total_amount 
                                      , sum(amount) over () 
                                   from t
                               )
                         group 
                            by name, symbol, dep
                    )
            )
      group         
         by grouping sets((name, symbol, dep), ())
      order by rank, max(rk) nulls last
    But I want to extract the following columns so... How can I do?

    Amount HR, % HRTotal, $HR Cumm Total,
    Finance amount, FinanceTotal %, $Finance Cumm Total
    Sales amount, a percentage of Total sales, $Sales Cumm Total.
    Amount marketing, MarketingTotal %, $Marketing Cumm Total


    as I want that all records, then will the dep..do-specific I need to use the case here?
    Thanks for all your time and effort in advance

    If I understand your needs, you need pivot: SQL and PL/SQL FAQ

  • Pick up the names of tables based on the value of the column

    I have a scheme in which I have 10000 tables and I want to pick up the names of tables in the schema where org_id is not equal to 1,
    Note: Org_id here is the column name.

    Could you please provide sql code me or a procedure to achieve this.

    Thanks in advance.

    This lthread can help

    How to find the column name and the name of the table with a value

  • Select column based on values in another table names.

    I would like to generate a sql statement based on the values in a table. For example, I would start "Select division from tableA".

    In the above example, 'division' would be a value of a column in TableB. Perhaps to looking like this.

    Table B

    The ColumnName of primary key
    -----
    -----
    Division of 1234
    Division of 3456
    Department of 7890

    I don't want back 'Division' of table B, based on the primary key = 1234 and then generate the SQL above.

    Any ideas?

    TIA

    It can be done through a PL/SQL block or the stored procedure.
    Below is a PL/SQL block to give you an idea:

    declare   NewColumnName varchar2(50);  SqlString     Varchar2(200);begin  select ColumnName into NewColumnName from TableB where PrimaryKey = 1234;  sqlString := 'select ' || NewColumnName || ' from TableA';  execute immediate sqlString;end;
    
  • How to get the value of a particular column column name?

    Hi all

    How to get the column name for a particular column value.
    example:

    create table test (ID number, col2, col3 varchar varchar);

    Insert into test values (1, 'true', 'false');
    Insert into test values (2, 'false', 'true');
    commit;

    I want to choose the name of the data column 'true' with id = 1;

    That is to say) while waiting for answer is "col2". pls help someone.

    This might help:

    DECLARE
       c1 SYS_REFCURSOR;
    BEGIN
       OPEN c1 FOR
       SELECT col2,
              col3
       FROM   test
       WHERE  id = 1;
       --
       FOR c IN (SELECT rownum rn,
                        t2.column_value.getrootelement() name,
                        EXTRACTVALUE(t2.column_value, 'node()') value
                   FROM TABLE(XMLSEQUENCE(c1)) t,
                        TABLE(XMLSEQUENCE(EXTRACT(column_value, '/ROW/node()'))) t2)
       LOOP
          IF c.value = 'true' THEN
             DBMS_OUTPUT.PUT_LINE(c.name);
          END IF;
       END LOOP;
    END;
    
  • Using PL/SQL to retrieve column names and column values

    If I have a table as follows

    Table has)
    meal varchar2 (32),
    drink varchar2 (32),
    VARCHAR2 (32)) desert.

    and the table contains a row

    drinks food desert
    -------------------------------------------------------
    Pork chops crispy Apple of iced tea


    Is it possible in pl/sql to retrieve the names of columns and values. I have an object type
    (OBJECT) ACE DATA_DEFINITION_T
    VARCHAR2 (32) 'FIELD_NAME ',.
    'FIELD_VALUE' VARCHAR2 (32)

    I need to store the column name in field_name and the value of column in field_value.

    So, the result would be:

    Field_name = meals
    Field_value = pork_chops

    Field_name = drink
    Field_value = iced tea

    Field_name = desert
    Field_value = croustade

    Thanks in advance.

    The Subscriber to the queue will pick up the message and how to process the data (field_value) based on the field_name (s). With the domain name, it cannot be what to do with the data.

    Sounds like an XML approach would be better than this owner = value field.

    You have considered things like [DBMS_XMLGEN | http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14259/xdb13gen.htm#i1025386]?

    Concerning
    Peter

  • As a dynamic values column names

    I have a WEEK_TAB table

    Week_num Bkg1 Bkg2
    1 10 20
    2 40 10
    3 30 20
    2 20 60
    1-10-50
    1-20-80
    3 10 30

    When I run this package, I get the below output...

    CREATE OR REPLACE
    PACKAGE GET_TOTAL AS

    TYPE ref_cursor IS REF CURSOR;

    PROCEDURE get_week_total (p_refCursor to ref_cursor);

    PROCEDURE get_total_val;

    END GET_TOTAL;
    /

    CREATE OR REPLACE
    PACKAGE BODY GET_TOTAL AS

    PROCEDURE get_week_total (p_refCursor to ref_cursor) AS
    BEGIN
    OPEN FOR P_refcursor
    SELECT SUM (bkg1), week_num
    OF week_tab
    GROUP BY week_num
    ORDER BY week_num;
    END get_week_total;

    PROCEDURE get_total_val AS
    v_refCursor ref_cursor;
    v_sum NUMBER;
    v_week NUMBER;
    v_total NUMBER: = 0;

    BEGIN

    get_week_total (v_refcursor);

    LOOP
    EXTRACTION v_refCursor
    IN v_sum, v_week;
    EXIT WHEN v_refcursor % NOTFOUND;
    v_total: = v_total + v_sum;
    DBMS_OUTPUT. Put_line (' week ' | v_week |': ' | v_sum);
    END LOOP;
    DBMS_OUTPUT. Put_line (' total sales reservations :'|| v_total);
    END get_total_val;

    END GET_TOTAL;
    /

    O/P
    Week 01:40
    Week
    Week 03:40
    Total sales reservations: 140

    --------------------------------------------------------------------------------

    Here, I'm moving the column name as dynamic value.
    I modified the package as below...

    CREATE OR REPLACE
    PACKAGE BODY GET_TOTAL AS

    CREATE OR REPLACE
    PACKAGE GET_TOTAL AS

    TYPE ref_cursor IS REF CURSOR;

    Strarray ARRAY TYPE IS VARCHAR2 (100);

    PROCEDURE get_week_total)
    p_colName VARCHAR2,
    p_refCursor to ref_cursor);

    PROCEDURE get_total_val;

    END GET_TOTAL;
    /

    CREATE OR REPLACE
    PACKAGE BODY GET_TOTAL AS

    PROCEDURE get_week_total)
    p_colName IN VARCHAR2,
    p_refCursor OUT ref_cursor) AS

    v_query VARCHAR2 (4000);
    BEGIN
    v_query: = ' SELECT SUM (: p), week_num FROM week_tab GROUP BY week_num ORDER BY week_num';

    P_refcursor OPEN FOR v_query
    Using p_colName;

    END get_week_total;

    PROCEDURE get_total_val AS
    v_refCursor ref_cursor;
    v_sum NUMBER;
    v_week NUMBER;
    v_total NUMBER: = 0;
    STRARRAY v_colName: = STRARRAY ('BKG1', 'BKG2');

    BEGIN

    I'm IN v_colName.FIRST... v_colName.Last LOOP
    get_week_total (v_colName (i), v_refcursor);

    LOOP
    EXTRACTION v_refCursor
    IN v_sum, v_week;
    EXIT WHEN v_refcursor % NOTFOUND;
    v_total: = v_total + v_sum;
    DBMS_OUTPUT. Put_line (' week ' | v_week |': ' | v_sum);
    END LOOP;
    DBMS_OUTPUT. Put_line (' total sales reservations :'|| v_total);

    END LOOP;
    END get_total_val;

    END GET_TOTAL; GET_TOTAL;
    /


    But I get this error message
    ORA-01722: invalid number
    ORA-06512: at "SCOTT. GET_TOTAL', line 29
    ORA-06512: at line 2


    Please let me know how this can be resolved... I'm trying to get the result as below

    Week 01:40
    Week
    Week 03:40
    Total sales reservations: 140

    Week 1:150
    Week 2:70
    Week 03:50
    Total sales reservations: 270

    Variable bind bind values of the object, not the object names. You cannot use bind variable as column name. Change:

    v_query := 'SELECT SUM (:p), week_num FROM week_tab GROUP BY week_num ORDER BY week_num'; 
    

    TO

    v_query := 'SELECT SUM (' || p_colName || '), week_num FROM week_tab GROUP BY week_num ORDER BY week_num'; 
    

    and

    OPEN p_refcursor FOR v_query
    USING p_colName; 
    

    TO

    OPEN p_refcursor FOR v_query; 
    

    SY.

Maybe you are looking for