Dynamic Pivot with Select Into

I have this Dynamic Pivot which works fine.
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
FROM [TEMP_lacp_factors]
ORDER BY '],[' + [factor_label]
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT * FROM
SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
FROM [TEMP_lacp_factors]
)t
PIVOT (MAX([factor_value]) FOR [factor_label]
IN ('+@years+')) AS pvt'
EXECUTE (@query)
I'm trying to take the results of that and do a SELECT INTO, so I can move the results to another table.  Is this possible?  I didn't find a whole lot online.
The error that I'm getting is this.
Caused by: Column name or number of supplied values does not match table definition.
How can I do this?  Is it even possible?
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

Sure, you can create a table with SELECT INTO, but it cannot be a #temptable. Well, it can be a #temptable, but it will disappear as soon as you exit the scope it was created it, that is the dynamic SQL.
The question is only, what would you do with this table later? Since you don't know the column names, about all work will have to be done through dynamic SQL.
A dynamic pivot is a non-relational operation. A SELECT statement produces a table, and a table describes a distinct entity, of which the column are distinct and well-defined attributes. Something which your dynamic pivot does not adhere to.
There is only one thing you can do with your dynamic pivot: returning the data to the client. I don't know what you want to do with that table, but probably you should do that manipulation before the dynamic pivot, because as I said: that is always your
last step.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • 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 Handle Dynamic Pivoting with a single SQL?

    I was searching for a single SQL who can dynamically understands the pivoting members in the data, I saw several ways of doing Pivoting depending on the version, some are really hard to understand but just two options upto now seams to be flexable enough to do dynamic pivoting, right?
    1- For this option you have to write PL/SQL block to build up the dynamic single SQL query, I also find this approach very easy to understand. :)
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:766825833740
    2- 11.1 's PIVOT new feature with PIVOT XML and ANY clause, a SINGLE SQL and easy to understand but returns XMLTYPE data, another step to parse to produce the report is needed.
    http://www.oracle-developer.net/display.php?id=506
    Below is a 10g Model Clause example, but here instead of pivoting by A1-A2-A3 staticly I want to have these values by a distinc subquery for example;
    create table test(id varchar2(2), des varchar2(4), t number);
    INSERT INTO test values('A','a1',12);
    INSERT INTO test values('A','a2',3);
    INSERT INTO test values('A','a3',1);
    INSERT INTO test values('B','a1',10);
    INSERT INTO test values('B','a2',23);
    INSERT INTO test values('C','a3',45);
    commit;
    SELECT * FROM test;
    ID DES T
    A a1 12
    A a2 3
    A a3 1
    B a1 10
    B a2 23
    C a3 45
    select distinct i, A1, A2, A3
    from test c
    model
    ignore nav
    dimension by(c.id i,c.des d)
    measures(c.t t, 0 A1, 0 A2, 0 A3)
    rules(
    A1[any,any] = t[cv(i),d = 'a1'],
    A2[any,any] = t[cv(i),d = 'a2'],
    A3[any,any] = t[cv(i),d = 'a3']
    I A1 A2 A3
    C 0 0 45
    B 10 23 0
    A 12 3 1 Any advice is appreciated, thank you.

    Hi,
    You can do dynamic SQL in SQL*Plus, also.
    [Thid thread|http://forums.oracle.com/forums/thread.jspa?messageID=2744039&#2744039] shows how to pivot a table with a dynamic number of columns.

  • Help with select into please

    Good morning everyone,
    I have a problem with my function. I need to do the dynamic select with the SELECT INTO
    create or replace function prueba (p_param IN VARCHAR2) RETURN VARCHAR2
    IS
    v_aux1 VARCHAR2(200);
    v_aux2 VARCHAR2(200);
    BEGIN
    SELECT col1
    INTO v_aux1
    FROM my_table
    WHERE col2 = p_param; --UNION SELECT '1233' FROM DUAL;
    RETURN v_aux1;
    EXCEPTION
    WHEN OTHERS THEN
    RAISE_APPLICATION_ERROR(-20000,SQLERRM );
    --RETURN v_aux2;
    END;
    When I try to call my function with the golden as follows:
    select (prueba('''MON'' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    OR
    select (prueba(chr(039)||'MON'||chr(039)||' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    I get the error: no data found
    If I use the sentence in Golden or SQLPLUS as follows:
    SELECT col1
    -- INTO aux1
    FROM my_table
    WHERE despaise = 'MON' UNION SELECT '12' FROM DUAL
    It ´s correct, and it return '1233'
    The value 'MON' no exists in my_table.
    If uncommented the sentence "UNION SELECT '1233' FROM DUAL" in my function an I use 'MON' as parameter it´s correct.
    How I can do this using the parameter with the UNION?.
    Thank you very much to all and sorry for my english

    Hi,
    welcome to the forum.
    Please read SQL and PL/SQL FAQ
    When you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    you cannot pass static SQL as part of the string.
    When you call the procedure in either wayselect (prueba('''MON'' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    select (prueba(chr(039)||'MON'||chr(039)||' UNION SELECT '||chr(039)||'12'||chr(039)||' FROM DUAL')) from dual
    This result in passing a whole string to your function as'MON' UNION SELECT '12' FROM DUAL
    which translates in your code asSELECT col1
    INTO v_aux1
    FROM my_table
    WHERE col2 = '''MON'' UNION SELECT ''12'' FROM DUAL'
    So it is searching a rows having col2 with value  '''MON'' UNION SELECT ''12'' FROM DUAL'
    Please try to explain what you are trying to achieve and we may help you.
    You could use dynamic SQL to do that but it is not clear what are your business requirement and the approach that you are using does not seem to be correct.
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Case with select into and sub query

    hi im trying to use case and select with sebqueries, but my beginer like understanding of syntax fails me. can someone point out what im doing wrong in the case select below. im using select into, as i ultimatly need to load a ref cursor for use with crystal reports.
    thanks
    james
    ps if anyone is london based, and would like to spend a day or two teaching me how to be a bit better at PL/SQL (can aford to pay a little bit) please get in touch!!
    SELECT
    Case (select kind_code from event where                    
    event.event_id = event.container_event_id)     
    when 1094006
    then          promo_name     
    end
    into      result
    FROM promo,     promo_plan ,     event_promotion
    WHERE      promo.promo_id = promo_plan.promo_id
    AND     promo_plan.promo_plan_id = event_promotion.promo_plan_id
    AND     event_promotion.detail_id = '33532282'
    when blah then 'blah';

    Hello
    AH i see what you are driveing at, yes i am just using case slect to determin which >routine to run, as the name is stored in a diferent location depending on the event kind >code. are are you saying i need multiple selects within the case statment? one for each >type of kind code?Well it depends really. If the select
    select kind_code from event where
    event.event_id = event.container_event_idIs going to return more than one row for any given run, you're going to need to take a bit of a different approach. Is it the case that this query will return more than one row which would mean that you want value X and value Y for each row?
    Using the test data and everything from before:
    SQL> CREATE OR REPLACE PROCEDURE p_GetStuff(ac_Result   OUT sys_refcursor)
      2  IS
      3
      4  BEGIN
      5     /*
      6             This uses a cartesian product i.e. repeat every row in
      7             dt_test_data against every row in dt_test_event
      8     */
      9     OPEN Ac_Result FOR
    10     SELECT
    11             CASE dt_test_event.kind_code
    12             WHEN 1 THEN
    13                     dt_test_data.object_name
    14             WHEN 2 THEN
    15                     dt_test_data.object_type
    16             END
    17     FROM
    18             dt_test_data,
    19             dt_test_event;
    20
    21  END;
    22  /
    Procedure created.
    SQL> var x refcursor
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    TABLE
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    TABLE
    TABLE
    TABLE
    TABLE
    INDEX
    INDEX
    INDEX
    INDEX
    INDEX
    20 rows selected.Or an alternative to that would be, if you have a fixed number of event ids and they relate to a fixed number of attributes you could use something like:
    CREATE OR REPLACE PROCEDURE p_GetStuff3(ac_Result     OUT sys_refcursor)
    IS
    BEGIN
              The SUBSTR
              is just there to make sure the data fit on screen, my SQL*Plus
              is a bit weird!
         OPEN Ac_Result FOR
         SELECT
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,1,dt_test_data.object_name,NULL)),1,30) attribute_1,
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,2,dt_test_data.object_type,NULL)),1,30) attribute_2
         FROM
              dt_test_data,
              dt_test_event
         GROUP BY
              object_name;
    END;
    SQL> delete from dt_test_event where kind_code=2;
    1 row deleted.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC                            TABLE
    ABC4                           TABLE
    AD1                            TABLE
    AD2                            TABLE
    ADHOC_CONTACT_LOG              TABLE
    AK_CD_CLAIM_VALIDATION_SOURCE  INDEX
    AK_CD_CLAIM_VALIDATION_TYPE    INDEX
    AK_CLAIM_ACTION_ROWSOURCE      INDEX
    APPROVAL_LIST_MEM_IE           INDEX
    APPROVE_GRP_HIST_IE            INDEX
    10 rows selected.Message was edited by:
    david_tyler
    Oops, copy + pasted the wrong comments for the 2nd proc.

  • Dynamic pivoting with 2 aggregation fields or more in sql server

    Hi,
    I have data like below:
    CrudeOilName
    Period
    YearValue
    MonthValue
    avgPrice_Ton
    GrothRate_Ton
    IPE BRENT
    Jan-13
    2013
    1
    243.516129
    245.016129
    NYMEX Light Sweet
    Jan-13
    2013
    1
    244.258064
    245.758064
    OPEC BASKET
    Jan-13
    2013
    1
    241.387096
    242.887096
    IPE BRENT
    Feb-13
    2013
    2
    237.392857
    238.892857
    NYMEX Light Sweet
    Feb-13
    2013
    2
    254.285714
    255.785714
    OPEC BASKET
    Feb-13
    2013
    2
    249.107142
    250.607142
    IPE BRENT
    Mar-13
    2013
    3
    238.193548
    239.693548
    NYMEX Light Sweet
    Mar-13
    2013
    3
    250.709677
    252.209677
    OPEC BASKET
    Mar-13
    2013
    3
    244.580645
    246.080645
    IPE BRENT
    Apr-13
    2013
    4
    255.566666
    257.066666
    NYMEX Light Sweet
    Apr-13
    2013
    4
    249.933333
    251.433333
    OPEC BASKET
    Apr-13
    2013
    4
    246.2
    247.7
    IPE BRENT
    May-13
    2013
    5
    255.645161
    257.145161
    NYMEX Light Sweet
    May-13
    2013
    5
    259
    260.5
    OPEC BASKET
    May-13
    2013
    5
    246.419354
    247.919354
    IPE BRENT
    Jun-13
    2013
    6
    242.233333
    243.733333
    NYMEX Light Sweet
    Jun-13
    2013
    6
    242.7
    244.2
    OPEC BASKET
    Jun-13
    2013
    6
    243.233333
    244.733333
    IPE BRENT
    Jul-13
    2013
    7
    241.451612
    242.951612
    NYMEX Light Sweet
    Jul-13
    2013
    7
    256.741935
    258.241935
    OPEC BASKET
    Jul-13
    2013
    7
    253.838709
    255.338709
    IPE BRENT
    Aug-13
    2013
    8
    252.032258
    253.532258
    NYMEX Light Sweet
    Aug-13
    2013
    8
    254.677419
    256.177419
    OPEC BASKET
    Aug-13
    2013
    8
    242.903225
    244.403225
    IPE BRENT
    Sep-13
    2013
    9
    251.966666
    253.466666
    NYMEX Light Sweet
    Sep-13
    2013
    9
    251
    252.5
    OPEC BASKET
    Sep-13
    2013
    9
    249.4
    250.9
    IPE BRENT
    Oct-13
    2013
    10
    236
    237.5
    NYMEX Light Sweet
    Oct-13
    2013
    10
    259.096774
    260.596774
    OPEC BASKET
    Oct-13
    2013
    10
    247.612903
    249.112903
    IPE BRENT
    Nov-13
    2013
    11
    245.2
    246.7
    NYMEX Light Sweet
    Nov-13
    2013
    11
    240.833333
    242.333333
    OPEC BASKET
    Nov-13
    2013
    11
    255.266666
    256.766666
    IPE BRENT
    Dec-13
    2013
    12
    245.774193
    247.274193
    NYMEX Light Sweet
    Dec-13
    2013
    12
    249.193548
    250.693548
    OPEC BASKET
    Dec-13
    2013
    12
    246.032258
    247.532258
    I need output like below:
    Period
    YearValue
    MonthValue
    [avgIPE BRENT]
    [avgNYMEX Light Sweet]
    [avgOPEC BASKET]
    Period
    YearValue
    MonthValue
    [GrowthIPE BRENT]
    [GrowthNYMEX Light Sweet]
    OPEC BASKET[Growth]
    Jan-13
    2013
    1
    243.516129
    244.258064
    241.387096
    Jan-14
    2014
    1
    245.016129
    245.758064
    242.887096
    Feb-13
    2013
    2
    237.392857
    254.285714
    249.107142
    Feb-14
    2014
    2
    238.892857
    255.785714
    250.607142
    Mar-13
    2013
    3
    238.193548
    250.709677
    244.580645
    Mar-14
    2014
    3
    239.693548
    252.209677
    246.080645
    Apr-13
    2013
    4
    255.566666
    249.933333
    246.2
    Apr-14
    2014
    4
    257.066666
    251.433333
    247.7
    May-13
    2013
    5
    255.645161
    259
    246.419354
    May-14
    2014
    5
    257.145161
    260.5
    247.919354
    Jun-13
    2013
    6
    242.233333
    242.7
    243.233333
    Jun-14
    2014
    6
    243.733333
    244.2
    244.733333
    Jul-13
    2013
    7
    241.451612
    256.741935
    253.838709
    Jul-14
    2014
    7
    242.951612
    258.241935
    255.338709
    Aug-13
    2013
    8
    252.032258
    254.677419
    242.903225
    Aug-14
    2014
    8
    253.532258
    256.177419
    244.403225
    Sep-13
    2013
    9
    251.966666
    251
    249.4
    Sep-14
    2014
    9
    253.466666
    252.5
    250.9
    Oct-13
    2013
    10
    236
    31
    247.612903
    Oct-14
    2014
    10
    237.5
    260.596774
    249.112903
    Nov-13
    2013
    11
    245.2
    240.833333
    255.266666
    Nov-14
    2014
    11
    246.7
    242.333333
    256.766666
    Dec-13
    2013
    12
    245.774193
    249.193548
    246.032258
    Dec-14
    2014
    12
    247.274193
    250.693548
    247.532258
    Please help ASAP.
    Regards,
    Srini

    Hi Srini
            I think if you want to scale with years also, you max need to consider the MonthValue as common value
    please try this
    Note: i have used the max() because i have avgPrice_Ton,GrothRate_Ton as in varchar in my example  you can modify as sum or avg if you want
    Drop table #temp1
    Select * into #temp1 From
    (select 'IPE BRENT' CrudeOilName,'41275' Period,'2013' YearValue,'1' MonthValue,'243.516129' avgPrice_Ton,'245.016129' GrothRate_Ton UNION ALL
    select 'NYMEX Light Sweet','41275','2013','1','244.258064','245.758064' UNION ALL
    select 'OPEC BASKET','41275','2013','1','241.387096','242.887096' UNION ALL
    select 'IPE BRENT','41306','2013','2','237.392857','238.892857' UNION ALL
    select 'NYMEX Light Sweet','41306','2013','2','254.285714','255.785714' UNION ALL
    select 'OPEC BASKET','41306','2013','2','249.107142','250.607142' UNION ALL
    select 'IPE BRENT','41334','2013','3','238.193548','239.693548' UNION ALL
    select 'NYMEX Light Sweet','41334','2013','3','250.709677','252.209677' UNION ALL
    select 'OPEC BASKET','41334','2013','3','244.580645','246.080645' UNION ALL
    select 'IPE BRENT','41365','2013','4','255.566666','257.066666' UNION ALL
    select 'NYMEX Light Sweet','41365','2013','4','249.933333','251.433333' UNION ALL
    select 'OPEC BASKET','41365','2013','4','246.2','247.7' UNION ALL
    select 'IPE BRENT','41395','2013','5','255.645161','257.145161' UNION ALL
    select 'NYMEX Light Sweet','41395','2013','5','259','260.5' UNION ALL
    select 'OPEC BASKET','41395','2013','5','246.419354','247.919354' UNION ALL
    select 'IPE BRENT','41426','2013','6','242.233333','243.733333' UNION ALL
    select 'NYMEX Light Sweet','41426','2013','6','242.7','244.2' UNION ALL
    select 'OPEC BASKET','41426','2013','6','243.233333','244.733333' UNION ALL
    select 'IPE BRENT','41456','2013','7','241.451612','242.951612' UNION ALL
    select 'NYMEX Light Sweet','41456','2013','7','256.741935','258.241935' UNION ALL
    select 'OPEC BASKET','41456','2013','7','253.838709','255.338709' UNION ALL
    select 'IPE BRENT','41487','2013','8','252.032258','253.532258' UNION ALL
    select 'NYMEX Light Sweet','41487','2013','8','254.677419','256.177419' UNION ALL
    select 'OPEC BASKET','41487','2013','8','242.903225','244.403225' UNION ALL
    select 'IPE BRENT','41518','2013','9','251.966666','253.466666' UNION ALL
    select 'NYMEX Light Sweet','41518','2013','9','251','252.5' UNION ALL
    select 'OPEC BASKET','41518','2013','9','249.4','250.9' UNION ALL
    select 'IPE BRENT','41548','2013','10','236','237.5' UNION ALL
    select 'NYMEX Light Sweet','41548','2013','10','259.096774','260.596774' UNION ALL
    select 'OPEC BASKET','41548','2013','10','247.612903','249.112903' UNION ALL
    select 'IPE BRENT','41579','2013','11','245.2','246.7' UNION ALL
    select 'NYMEX Light Sweet','41579','2013','11','240.833333','242.333333' UNION ALL
    select 'OPEC BASKET','41579','2013','11','255.266666','256.766666' UNION ALL
    select 'IPE BRENT','41609','2013','12','245.774193','247.274193' UNION ALL
    select 'NYMEX Light Sweet','41609','2013','12','249.193548','250.693548' UNION ALL
    select 'OPEC BASKET','41609','2013','12','246.032258','247.532258' UNION ALL
    select 'IPE BRENT','41306','2014','2','237.392857','238.892857' UNION ALL
    select 'NYMEX Light Sweet','41306','2014','2','254.285714','255.785714' UNION ALL
    select 'OPEC BASKET','41306','2014','2','249.107142','250.607142' ) a
    Declare @sql Nvarchar(4000)='select MonthValue'
    select @sql = @sql +',MAX(case when CrudeOilName='''+ CrudeOilName+''' and YearValue= ''' + YearValue +''' then avgPrice_Ton else null end) as ['+YearValue+'_'+CrudeOilName+'avgPrice_Ton]'+CHAR(13)
    +',MAX(case when CrudeOilName='''+ CrudeOilName+''' and YearValue= ''' + YearValue +''' then GrothRate_Ton else null end) as ['+YearValue+'_'+CrudeOilName+'GrothRate_Ton]'+CHAR(13)
    from
    (select distinct YearValue,CrudeOilName From #temp1 ) a
    select @sql=@sql + 'from #temp1 group by MonthValue order by convert(int,MonthValue)'
    Print @sql
    EXEC sp_executesql @sql
    Thanks
    Saravana Kumar C

  • FORMS_DDL with select into

    Hi,
    Here my code for un dynamic query in ORACLE FORMS
    ls_query:=' select count(*) into '     ||     pkg_hist.pkg_count_pdt ||' from      FN_WAVE_PROD_HIER_DETAIL where PROD_HIER_ID='||:b_produit.PROD_HIER_ID      ||' and division ='|| :b_produit.division || pkg_and_clause ;
    Forms_ddl ( ls_query );
    /* Where pkg_and_clause contains the dynamic statement
    and pkg_hist.pkg_count_pdt is a package variable
    I got the following error : ORA-24374: define not done before fetch or execute and fetch
    Does this code can works ?
    regards
    Edited by: Totem92 on 3 août 2011 07:57

    This forum is about C programming in general, and about using the Studio C compiler. Your question is about Oracle database programming. I suggest you try a database forum here:
    http://forums.oracle.com/

  • Problem with SELECT INTO Query

    Why am I always getting 0 for returnvalue in the following query?
    create or replace
    PACKAGE BODY MyPKG AS
    PROCEDURE SelectCount
       returnvalue       OUT      INTEGER
    AS
      BEGIN
    select COUNT(*) from MyTable into returnvalue;
    IF( SQL%ROWCOUNT >= 1 )
      THEN
        returnvalue := 1;
      ELSE
        returnvalue := 0;
      END IF; 
    dbms_output.put_line('returnvalue: ' || returnvalue);
    END SelectCount;
    END MyPKG ;

    Hi,
    When you use an aggregate function, such as COUNT, without a GROUP BY clause, then the query is guaranteed to return exactly 1 row, regadless of whether there are any rows in the table or not.
    Perhaps you meant:
    create or replace
    PACKAGE BODY MyPKG AS
    PROCEDURE SelectCount
       returnvalue       OUT      INTEGER
    AS
      BEGIN
          select COUNT(*) from MyTable into returnvalue;
          dbms_output.put_line('returnvalue: ' || returnvalue);
      END SelectCount;
    END MyPKG ;
    that is, simply lose the IF block.

  • Order columns in dynamic pivot

    I have the following query that works well, except that the columns (hours) are not sorted. 
    --Get distinct values of the PIVOT Column
    SELECT @ColumnName= ISNULL(@ColumnName + ',','')
    + QUOTENAME([hour])
    FROM (SELECT DISTINCT [hour] FROM #temp) AS Courses
    --Prepare the PIVOT query using the dynamic
    SET @DynamicPivotQuery =
    N'SELECT EmpId, ' + @ColumnName + '
    FROM #temp
    PIVOT(SUM(Total)
    FOR [hour] IN (' + @ColumnName + ')) AS PVTTable'
    --Execute the Dynamic Pivot Query
    select @DynamicPivotQuery
    EXEC sp_executesql @DynamicPivotQuery
    The resultset for the following dynamic pivot, the [hours] are the top:
    EmpId [23] [15] [12] [21] [18] [10 [19] [13] [22]...
    704 9 2.43 8.5 3.2 29 1.2 2.3 29 1.2 ...
    As you can see the hours are not sorted. I would like to display them sorted descending.
    thanks
    VM

    Using the method I posted in your previous question, there is sorting built in:
    CREATE TABLE #table (name VARCHAR(20), date DATE, hr CHAR(2), min CHAR(20), amt INT)
    INSERT INTO #table (name, date, hr, min, amt) VALUES
    ('Joe ', '20150320', '08', '00', 5),('Joe ', '20150320', '08', '15', 3),('Carl', '20150320', '09', '30', 1),
    ('Carl', '20150320', '09', '45', 2),('Ray ', '20150320', '13', '00', 8),('Ray ', '20150320', '13', '30', 6),
    ('Patrick', '20150320', '14', '30', 6),('Patrick', '20150320', '15', '30', 6),('Patrick', '20150320', '16', '30', 6)
    DECLARE @dSQL NVARCHAR(MAX), @pivotCols NVARCHAR(MAX)
    ;WITH base AS (
    SELECT CAST('['+hr+']' AS NVARCHAR(MAX)) AS string, ROW_NUMBER() OVER (ORDER BY CAST(hr AS INT) DESC) AS seq
    FROM #table
    GROUP BY hr
    ), rCTE AS (
    SELECT string, seq
    FROM base
    WHERE seq = 1
    UNION ALL
    SELECT a.string +',' + r.string, a.seq
    FROM base a
    INNER JOIN rCTE r
    ON r.seq + 1 = a.seq
    SELECT @pivotCols = string
    FROM rCTE
    WHERE seq = (SELECT MAX(seq) FROM rCTE)
    SET @dSQL = 'SELECT name, date, '+@pivotCols+'
    FROM (
    SELECT name, date, amt, hr
    FROM #table
    ) s
    PIVOT (
    SUM(amt) FOR hr IN ('+@pivotCols+')
    ) p
    GROUP BY name, date, '+@pivotCols
    EXEC sp_executeSQL @dSQL
    DROP TABLE #table
    The columns are sorted by:
    ROW_NUMBER() OVER (ORDER BY CAST(hr AS INT) DESC)
    It produces:
    name date 08 09 13 14 15 16
    Carl 2015-03-20 NULL 3 NULL NULL NULL NULL
    Joe 2015-03-20 8 NULL NULL NULL NULL NULL
    Patrick 2015-03-20 NULL NULL NULL 6 6 6
    Ray 2015-03-20 NULL NULL 14 NULL NULL NULL
    Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

  • Select Into statement in db function - query from granted schema table

    problem with "select into" in db function in 10.2
    There are two schemas. 'mdbdev' is the master database and 'devusr' is granted SELECT table access to execute queries in mdbdev schema.
    with devusr, in SQL, I'm able to execute the following query
    select wm_concat(strConcatedCountryList)
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <param?>
    order by country_name)
    but when I use the same query in function/procedure with "select into", the compilation failed with error *"table or view does not exist"*
    FUNCTION GETCOUNTRYLISTTOSHIP (SHIP_STATUS IN NUMBER)
    RETURN VARCHAR2
    IS
    var2CountryList VARCHAR2(1000);
    BEGIN
    select wm_concat(strConcatedCountryList) INTO var2CountryList
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <value of SHIP_STATUS>
    order by country_name);
    return var2CountryList;
    END;
    Please advise/help/hint :)

    David, Justine, Thank you. The facts from this forum post helped a lot to get the solution.
    The query helped a lot (select * from all_tab_privs_recd where owner = 'MDBDEV' and table_name = 'COUNTRY_MASTER").
    there was a grant using ???(donno wht DBA said) and no direct SELECT grant on that country_master to "devusr". grant command executed. Now, it works :)

  • IR with dynamic pivot

    Hi all
    We have been designing resource management system and want to provide flexible way to extend resource properties at runtime. So we are storing resource properties in a single table, e.g.
    select * from _kv
    ID K V
      1  name Bob
      1  age  30
      1  gender male
      2  name Susan
      2  status married
    convert to
    +-----+-------+--------+----------+
    | key | color | height | whatever |
    +-----+-------+--------+----------+
    | 1   | green | 15     | ---      |
    | 2   | ---   | ---    | lol      |
    +-----+-------+--------+----------+
    example of dynamic pivot Dynamic SQL Pivoting &amp;#8211; Stealing Anton&amp;#8217;s Thunder&lt;/title&gt; //&lt;title&gt;AMIS Technology Blog…
    Is it possible to create interactive report with dynamic columns updated when _kv will be changed?
    Is it possible to create add/edit dynamic form depends on key set if we add value type description?
    Thanks

    make sure you put some thought into your database design before you go too far.
    There are many horror stories about EAV based schema designs. (which this design seems to be heading.)
    Read up on them before you go too far.
    -- back to being on topic --
    AFAIK you can not do dynamic SELECT with an Interactive Report.
    However, you can with a Basic Report.  But, it is non-trivial. (ie it is difficult to do)
    Basic Report can use a "function returning SELECT statement".
    You will also need to name the columns based on a different function.
    In order to 'synchronize' the column names with the SELECT statement, you will need a 3rd function that properly generates them.
    This 3rd function MUST have an 'ORDER BY' clause.
    Both the generateSELECT() function and the generateCOLUMN_NAMES() function will call that 3rd function.
    From a code management standpoint, you will need to create a package that contains all three functions.
    are you sure you want to go this route?
    are you ready to go this route?
    Again, think about your table designs.
    MK

  • Select with out into in plsql

    hi all
    i want to write a select statment in a procedure with out into statement ..
    is it possilbe if yes how can i do this.
    if its not possible then if we have to Return a number of rows from procedure then how can i do this..
    thanks in advance

    User1728 wrote:
    actual i want to return a datatable type data from procedureWhat does "datatable type" mean? "Datatable" is not a type in PL/SQL, so I assume that it has some meaning in your client programming language. What Oracle data type are you trying to return?
    My guess would be that you are trying to return a REF CURSOR so that you want something like
    SQL> create procedure return_rc( p_rc OUT sys_refcursor )
      2  as
      3  begin
      4    open p_rc for select * from emp;
      5  end;
      6  /
    Procedure created.
    SQL> variable rc ref cursor;
    Usage: VAR[IABLE] [ <variable> [ NUMBER | CHAR | CHAR (n [CHAR|BYTE]) |
                        VARCHAR2 (n [CHAR|BYTE]) | NCHAR | NCHAR (n) |
                        NVARCHAR2 (n) | CLOB | NCLOB | REFCURSOR |
                        BINARY_FLOAT | BINARY_DOUBLE ] ]
    SQL> variable rc refcursor;
    SQL> exec return_rc( :rc );
    PL/SQL procedure successfully completed.
    SQL> print rc
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800
            20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300
            30
          7521 WARD       SALESMAN        7698 22-FEB-81       1250        500
            30
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM
        DEPTNO
          7566 JONES      MANAGER         7839 02-APR-81       2975
            20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400
            30
    <<more data snipped>>Justin

  • Dynamic page with multiple select in where clause

    Hi,
    I have a dynamic page and in the where-clause, i have a bind variable. In a report i use for instance
    and rtrim((to_char(date_time5,'DAY'))) IN :v_day
    That works ok in a report. But it does not work in a dynamic page.
    what code is needed to work with a multiple select box on the customize screen for a dynamic page?
    Thanks.

    Hi.
    I have a dynamic page, with a bind variable :v_day. On the customization screen the user can select one or more days of the week, or all days. I use this also in a report and then it works ok. In the where clause i use:
    and rtrim((to_char(date_time,'DAY'))) IN :v_day
    Date_time is a tablecolumn (date).
    When i add this line in the select script from the dynamic page, i get error:
    : ORA-06550: line 1, column 2443:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
    The symbol "(" was substituted for "" to continue.
    ORA-06550: line 1, column 2606:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    . ( ) , * @ % & - + / at mod rem <an exponent (**)> and or ||
    The symbol ")" was substituted for ";" to continue.
    ORA-06550: line 1, column 3236:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
    The symbol (WWV-11230)
    Critical Error in wwerr_api_error.get_errors! SQL Error Message: ORA-06502: PL/SQL: numeric or value error: character string buffer too small (WWV-)
    Thanks.

  • DYNAMIC PIVOT - Problem with variables

    Dear All,
    I'm working on a Query that makes use of Dynamic Pivot
    It is intented to give a summarized list of Income and Expenses month by month
    I have adapted the foll. Query from SAP B1 Forum to my problem:
    Re: Date Wise Production Report
    Unfortunately my adaptation does not work.
    When I run it, the following Selection Criteria screen appears. I input the dates as below:
    Query - Selection Criteria
    Posting Date        Greater or Equal            01.01.11
    Posting Date        Smaller or Equal            31.12.11
    [OK]      [Cancel]
    On pressing [OK], I receive this error message:
    Incorrect Syntax near 20110101
    Grateful if anybody could help me spot my mistake (It's likely to be within Section 2)
    Thanks
    Leon Lai
    Here's my adapted SQL
    /*Section 1*/
    DECLARE @listCol VARCHAR(2000)
    DECLARE @query VARCHAR(4000)
    /*Section 2*/
    SELECT @listCol =
    STUFF(
    ( SELECT DISTINCT
    '],[' + CONVERT(VARCHAR, MONTH(T0.RefDate), 102)
    FROM JDT1
    FOR XML PATH('')
    , 1, 2, '') + ']'
    /*Section 3*/
    SET @query =
    SELECT * FROM
    SELECT
    T0.Account,
    T1.GroupMask,
    T1.AcctName,
    MONTH(T0.RefDate) as [Month],     
    (T0.Debit - T0.Credit) as [Amount]
    FROM dbo.JDT1 T0
    JOIN dbo.OACT T1 ON T0.Account = T1.AcctCode
    WHERE
    T1.GroupMask IN (4,5,6,7) AND
    T0.[Refdate] >= '[%1]'AND
    T0.[Refdate] <= '[%2]'
    ) S
    PIVOT
    Sum(Amount)
    FOR [Month] IN ('+@listCol+')
    ) AS pvt
    /*Section 4*/
    EXECUTE (@query)

    Hi,
    try to update where condition as  :
    T0.[Refdate] >= ' + cast ([%1] as nvarchar) + ' AND
    T0.[Refdate] <= ' + Cast([%2] as Nvarchar) + '
    Thanks,
    Neetu

  • Dynamic LOV with dates and selected default value

    Hello,
    I have a dynamic lov with dates. Query looks like this:
    select distinct concat(to_char(b.send_day_time,'YYYY.MM.DD HH24'),':00') display_value, to_char(b.send_day_time,'YYYY.MM.DD HH24') return_value
    from ...
    No I want to select a specific date as the default value. I put the following code for the default value:
    declare
    begin
    return to_char ('2008.02.19 10:00');
    end;
    But it doesn't work.The date (string) exists in the lov but it is not selected.
    Can someone tell me where the problem is?
    Thx in advance.
    Greetings,
    hamburger

    Hi hamburger,
    As return value you specified to_char(b.send_day_time,'YYYY.MM.DD HH24'),
    so your default value should be like to_char('2008.02.19 10'). Also pay attention to select the "Default Value Type".
    Hope this helps.
    chrissy

Maybe you are looking for

  • How to pass 100+ tags in a single sql/tag query

    <b>In my current application I have to pass 180+ tags in a single query to retrieve data from iHistorian. I want to know how to pass more thatn 100 tags in a single SQL or TAG Query using OLEDB or UDC connectors. If anybody has done it in the past ,p

  • Delete multiple document libraries in SharePoint 2013

    We currently have 2000+ site collections where I would like to delete the default "Documents" library. I know how to do this manually for one site collection and it works fine when I use this: $web = get-spweb -Identity http://intranet/linktoasite $l

  • IR-Filter and download CSV

    Dear all, the behaviour of pre-setting IR-filters with apex_util.ir_filter is not really clear to me. Suppose I have the following scenario: *1)* on page 200 I have an interactive report: select to_char(hiredate,'yyyy') as hiredate, job, sal from emp

  • When does a method do too much?

    so I'm trying to write cleaner and more effective code, but one of the problems i always find myself in is that i never know how large a method should be. obviously its relative to the job it's doing and such, but i was wondering if there was some so

  • Just had to re-build my MacBook Pro.

    When using to iTunes to backup the iPhone now, I want to move the Contact from iPhone to the Mac and it seems to keep trying to delete the contact from the iPhone.  Don't want this to happen.  Anyone know how to get the New iTunes app to truly copy t