Turning sql  string (with dynamic columns) into a pipelined function

Hi guys,
I was working on an apex report the other day, and wrote the sql below (for those who don't know apex well, in an apex report you can define the columns at runtime.) When I was finished, I said to myself: "It would be great to have a pipeline function with this capability." So, the idea would be to have a sql string where the columns are created dynamically, depending on input parameters - and then be able to use this sql everywhere (oracle reports, sqlplus) through a pipelined function.
Here's the sql (simplified, of course, the data itself is actually not important - the LOOP is the key)
declare
v_sql varchar2(4000);
begin
v_sql := 'select client, ';
for i in (select employee from company_employees_view where condition = pi_parameter order by 1) loop
v_sql := v_sql || sum(decode(employee,''' || i.employee || ''', total)) "' || i.employee || '"';
end loop;
v_sql := v_sql || ', sum(total) "Total"';
v_sql := v_sql || ' from company_employees_view group by client';
end;
This sql would result in a final product like:
select client
, sum(decode(employee,'John',total) "John"
, sum(decode(employee,'Paul',total) "Paul"
, sum(decode(employee,'George',total) "George"
(and so on... this sql could have more or less columns depending on the input parameters of the function)
from company_employees_view
group by client;
I have tried feeding this sql into a ref cursor and an object, but always received an "inconsistent datatypes" message.
The object would be something like:
create or replace object rt_employee as (total number);
create or replace tt_employee as table of rt_employee;
create or replace object rt_client as (
client varchar2(100),
employee tt_employee);
create or replace tt_client as table of rt_client;
(I am not paying too much attention to syntax here.)
By the way, no hurry whatsoever, this is just for fun, take your time. I am using database XE with apex 2.1 and sql developer 1.2.
Thanks, Roger

This is the only solution I've ever seen to dynamic pipelined columns...
How to pipeline a function with a dynamic number of columns?

Similar Messages

  • Importing From Flat File with Dynamic Columns

    HI
    I am using ssis 2008,i have folder in which I have Four(4) “.txt” files each file will have 2 columns(ID, NAME). I loaded 4
    files in one destination, but today I receive one more “.txt” file here we have 3 columns (ID, NAME, JOB) how can I get a message new column will receive in source. And how can I create in extra column in my destination table dynamically …please help me

    Hi Sasidhar,
    You need a Script Task to read the names and number of columns in the first row of the flat file each time and store it in a variable, then create a staging table dynamically based on this variable and modify the destination table definition if one ore more
    new columns need to be added, and then use the staging table to load the destination table. I am afraid there is no available working script for your scenario, and you need some .NET coding experience to achieve your goal. Here is an example you can refer
    to:
    http://www.citagus.com/citagus/blog/importing-from-flat-file-with-dynamic-columns/ 
    Regards,
    Mike Yin
    TechNet Community Support

  • Creating Query with dynamic columns to show results

    Hi experts,
    I need to know how to create a query with dynamic columns. Meaning, I don't want to create a query with fixed columns representing the 12 periods of the fiscal year to show me actuals as the fiscal year proceeds.
    For example, if I am currently in the middle of period 3 (March) of a fiscal year, when I execute the query, I need it to automatically only show me the 'Actuals' for periods 1 and 2, without seeing the columns from periods 3 to 12 showing blank.
    Then when I am in the middle period 5 (May) the query should ONLY show me the columns for periods 1 to 4 'Actuals', no results should be shown for periods 5 to 12 yet, and I don't want to even see blank columns for period 6 to 12.
    How do I define my columns, to achieve this.
    Maximum points will be awarded.
    Thanks Everyone.

    Hi Josh,
    I'm having a little difficuluty understanding what should be included in my restricted key figures.
    The time characteristics that I have available to use are:
    0FISCPER3 (posting period)
    0FISCYEAR (fiscal year), currently using SAP EXIT to default current fiscal year.
    0FISCVARNT (fiscal year variant).
    In addition, I have the following characteristics available to be used in the columns:
    Value type (10)
    version (currently I'm using variable for it)
    Currency type (020)
    Currency (USD).
    Can you explain what my restricted key figure should be based on and how it should look.
    I tried to create a restircted key figure using 0AMOUNT, and 0FISCPER3. For 0FISCPER3  I created a range from 1 to previous period (using SAP EXIT that supplied previous period).I also had value type, version, currency type, and currency included in that restricted key figure.Then when I tried to drag 0FISCPER3 under the restricted key figure once again, it wouldn't let me, probably because I've already used 0FISCPER3 in the restricted key figure.
    Please let me know if my explanation is not clear.
    Your step by step help would be great.
    Thanks
    Edited by: Ehab Mansour on Sep 23, 2008 2:40 PM

  • DataTable with dynamic columns

    Does somebody have an example of how to code a h:dataTable with dynamic columns? I have seen hints about how to do it in these two articles:
    http://forum.java.sun.com/thread.jspa?forumID=427&threadID=5218508
    http://forum.java.sun.com/thread.jspa?threadID=577589&messageID=2909047
    but a complete working example would be really helpful.
    I think the key is understanding the "binding" parameter to h:dataTable but I'm having a hard time understanding it. Thanks.

    I found it here:
    http://balusc.blogspot.com/2006/06/using-datatables.html#PopulateDatatable

  • Logic to upload file with dynamic columns

    hi
    in my requirement i hav given to add logic to upload file with dynamic columns so that this upload program can be reused.
    this way the program is flexible, irrespective of the number of columns in the file.
    can any one explain this?
    and let me know what actually i hav to do.

    Check the program and the dynamic column is in the col_pos internal table and in the routines get_structure onwards.
    https://www.sdn.sap.com/irj/sdn/wiki?path=/display/scm/dynamic%2bstructures%2band%2bcomponents
    cheers
    Aveek

  • Difficult to achive the report layout with dynamic column names

    I have a report layout as below.
    So here the column names are dynamic.And each fixed row group has different calculations. I have a date parameter. If I select July 2013, then I need to show data from July 2012 to July 2013 with Columns(Jul-12, Aug-12...Jul-13). How to achive below layout
    with dynamic columns?

    Hi Sarayu_CM,
    According to your description, you want to filter the records of prior year based on only one parameter selection. Right?
    In this scenario, we can create two parameters. The first one is for user to select. The second parameter is based on the first parameter selection. We don't need to specify Available Values for the second parameter, but we should use expression to specify
    Default Values based on the first parameter selection. Use the expression below:
    =DateAdd("m",-12,FormatDateTime(Parameters!param1.Value))
    Then we just need to apply a filter on the matrix/dataset to get the records which the date is between values in these two parameters.
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou

  • Form with dynamic Column Names

    Hello,
    I am using "Form with report on table" and I would like to make use of dynamic column names labels that are derived from another table (sql). I am stuck on how to do this, any advice?

    Hi FourEyes;
    Try using this.
    Select Col1, Col2, Col3
    into :P1_Field1, :P1_Field2, :P1_Field3
    from Your_Table
    Where (your conditions);

  • Concatenate strings from a column into a single row

    I am trying to string values from a column into a single row. I need a list of students (one row per student) with their phone number and they could have more than one number. I found a function that should do what I need but the syntax is for SQL Server, not SQL*Plus. I've tried several variations but can not come up with the correct syntax.
    This is the SQL Server version:
    CREATE FUNCTION dbo.GetPhoneList(@StudentID int)
    RETURNS varchar(500) AS
    BEGIN
    DECLARE @StringList varchar(500)
    SELECT @StringList = COALESCE(@StringList + ‘, ‘, ”) + Telephone.PhoneNumber
    FROM Telephone t
    WHERE t.StudentID = @StudentID
    IF @StringList IS NULL
    SET @StringList = ‘No Phone’
    RETURN @StringList
    END
    SQL*Plus does not like the @ symbol, so I tried taking that out. I've put semi-colons where I think they should be, but I still get various error messages. Any suggestions?
    Thanks.

    Hi,
    What you want to do is called "String Aggregation"
    You could write a PL/SQL funcrtion to do that for a specific column in a specific table, but [this page|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] has a couple of different generic solutions that will work on any tables and columns.
    I recommend the first soluton, the user-defined function STRAGG, which you can copy from that page.
    Once you have STRAGG installed, your query can be something like:
    SELECT     s.student_id
    ,     NVL ( STRAGG (t.phone_number)
             , 'No phone'
             )     AS phone_nums
    FROM          student          s
    LEFT OUTER JOIN     telephone     t     ON s.student_id     = t.student_id
    GROUP BY     s.student_id;On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.
    It lokks like
    Edited by: Frank Kulash on Feb 10, 2009 6:31 PM

  • DataGrid with dynamic columns & renderers

    I'm developing using Flash Builder 4 & Flex SDK 4.1.
    I need to manage very dynamic DataGrid components and keep their definitions, which are all part of a complex item renderer of an Offers list.
    The objects structure is simplified as follows -
    Data: Model --> Offers ArrayCollection --> Offer VO --> DataGrid data ArrayCollection & DataGrid columns Array
    View: List --> Offer Item Renderer --> DataGrid
    1. Since the DataGrid's columns property accepts only an Array (not ArrayCollection), it seems like Data Binding for defining the columns is very problematic.
    I tried to bind it to the source property of an ArrayCollection that would keep my columns definitions, but it didn't really work (mainly header display bugs).
    What is the recommended way to keep the dynamic columns definition of a DataGrid?
    2. Each column can have a set of dynamic properties, so I created a "mutant" - Column VO that extends DataGridColumn and got a dynamic properties ArrayCollection on it.
    The columns got a custom header renderer that includes an icon when there are properties.
    The header renderers got 4 main states (NotSelectedWithProperties, SelectedWithProperties, NotSelectedWithoutProperties & SelectedWithoutProperties).
    However, the header renderer area seems a bit buggy when maintaning dynamic columns.
    Any thoughts on the subject?
    3. Anyway, I ended up recreating the DataGrid's columns Array very often (copying the columns definition on the offer's item renderer's dataChange event handler).
    Note that the dynamic properties can be edited when the column is selected and I copy their values from the view back to the model when entering the state NotSelectedWithProperties.
    This feels way too complicated and I really try to keep it simple, inspite of the required complexity.
    Does anyone have better ideas?
    4. In some cases the column's item renderer should also be modified into another DataGrid (grid-in-grid).
    I used the MXDataGridItemRenderer with a DataGrid and included an ArrayCollection for the "newValue" returned by the editor.
    (I use RendererIsEditor=true and on updateComplete populate that variable with the DataGrid's dataProvider contents)
    When needed, I loop though the data objects of the parent DataGrid and populate the related field with an ArrayCollection of key-value objects that are displayed on the internal DataGrid.
    After adding this feature I encounter very strange bugs -
    a. After editing the grid-in-grid values and changing the column's state (selecting & deselecting), I get the following exception:
    ArgumentError. Error #2025: The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/setChildIndex()
    at mx.core::UIComponent/setChildIndex().......6993....
    All I could find about this is that it might be related to some context error or something, but I'm really stuck on this one.
    b. Sometimes another column might copy value from one row to another, running over the previous value.
    I'm not sure exactly what sequence of actions causes this behavior, but it's related to that itemRenderer for sure.
    c. Switching places with a column that uses the grid item renderer (headerShift) causes a stak overflow of StyleManager that tried to get style from the DataGridItemRenderer. This one I just found out, but couldn't reproduce a second time... strange!
    I'm pretty sure this caused another problem that I don't remember at the moment.
    The bottom line is that there got to be a better way to implement this feature within this already-complicated environment.
    Maybe I'm doing something very wrong here...
    Please advice and thanks for reading all this.

    Update on item 4a -
    This was a major issue (the main reason for opening this thread really) and I managed to resolve it!
    As part of my application, I override the default DataGrid behavior for column selection (headerRelease event).
    Instead of sorting, I change the column's header looks and define it as Selected (for showing its dynamic properties and enable its deletion).
    At first I did this by setting styles, but the look didn't refresh unless I created a new instance of the header renderer.
    Later I changed thi behavior to work with states, but I left the new header renderer instance creation commands and those lines created all the mess!
    Conclusion -
    If you define a custom header renderer for your datagrid column and then a custom item renderer, don't create a new instance of your header renderer!
    It would still be nice to get some response for the other issues I raised.
    Thanks and have a nice week.

  • GoNav function with dynamic columns 10g

    Hi,
    I have a report with a dashboard prompt that dynamic change the report column. The result of this prompt is set into a presentation variable @{dimension}.
    Now I want to use the GoNav function on the column that dynamically changes.
    The data format for this column should be:
    @[html]"<font class="Nav" onclick=\"javaScript:GoNav(event, '/users/Administrator/Test', 'Department', 'Department_name' ,'"@"','_self');\">"@"".
    But this syntax only works for the column Department.Department_name. If the prompt on the dashboard is changed to another column the navigate link doesn't work anymore.
    Is there a solution to make this work so that also the column can be set dynamically for the navigation?

    I have a report with a dashboard prompt that dynamic change the report column. The result of this prompt is set into a presentation variable @{dimension}.
    Now I want to use the GoNav function on the column that dynamically changes.
    The data format for this column should be:
    @[html]"<font class="Nav" onclick=\"javaScript:GoNav(event, '/users/Administrator/Test', 'Department', 'Department_name' ,'"@"','_self');\">"@"".
    But this syntax only works for the column Department.Department_name. If the prompt on the dashboard is changed to another column the navigate link doesn't work anymore.
    As per your comments above you are using Column selector kind of functionality using a Dashboard prompt and in your GO nav you are taking column Department that's way it is working for that column only , if you change the Column in Dashboard prompt also still GO nav point to Department column only...make the GO NAV to take dynamic columns..
    I am not sure whether we can pass presentation variable .....with my knowledge its not..use GO URL instead of GO NAV

  • Problem with dynamic column in SBWP

    Hi Friends,
    In SWL1 I have created two attributes with header as "CANCELLED" and " DESCRIPTION" for a particular task.But my SBWP is still showing columns as "Dynamic column" for the workitems of that task.
    Please help me on this.
    Thanks.
    Dilip

    Hi Dilip,
    The column headings will only appear in the task-specific view. In other words, by default the headers will be generic because you can have mixed tasks in the worklist, and column 1 can be a date for one task and a company name for another.
    The user needs to expand the tree on the left hand side and navigate to the "Approve Purchase Order" (or whatever) node to show only items of that task, then column headers should show up.
    Regards,
    Mike

  • Problem with dynamic columns in smartforms.

    Dear SDN Experts,
    I have a requirement in smartforms for dynamic columns.
    i have used template with 10 columns, So from these 10 columns,Columns may vary monthly MIN 2 to MAX 10 depending on
    readings with them  for that month.
    i cannot fix column headings also,Because headings also changes dynamically.
    So Problem is if there is no data in columns,Columns is displayng empty.
    For EX: In this month i have 2 columns data remaining all columns is displaying empty boxes.
    Please suggest me a solution  is this posible in smartforms if i use table also.
    <removed by moderator>
    Regrds,
    MNR
    Edited by: Thomas Zloch on Sep 11, 2011 3:50 PM

    Hi friend,
    See the link below it is having the solution of hiding the columns in smart forms
    Hide table columns in smart form?
    Create a table to display your values with 12 col and hide the columns based on the idea provided in the link above.
    I think this will solve your issue if you still have queries please revert back to me i will help you.
    Thanks,
    Sri Hari

  • Pivot Table with Dynamic Columns and Headers

    Hello,
    I'm trying to pivot a table of data where the column headers will be dynamic.  While I know how to pivot the table to get what I want how will I be able to pick up the table column header from the Pivot to display in the report?
    For example:
    Unpivoted data is Employee Code, Branch Code, Problem Code, # of Problems.
    There is many records for a given Employee and Branch that I want to pivot so the Column headers are the Problem Codes and the data below is the SUM(num_problems) for that Problem.
    So the data may look like this for Tech Bob, Branch NY.
    Problem = LEAK, Num_problem = 5
    Problem = DAMAGE, Num_problem = 2
    Problem = OTHER, Num_problem = 3
    Which problem codes may appear is unknown but selecting the DISTINCT(problem) across all techs gives me the column headings to use.
    So if I pivot this data, I get this Row:
    Tech = Bob, Branch = NY, DAMAGE = 2, LEAK = 5, OTHER = 3
    So first can SSRS handle having dynamic columns?  Only Tech and Branch are known and the remaining columns are dynamic based on how many Problems they worked on.
    Second, how can I set the column heading in my Tablix to be the Problem Code?
    Sherry

    You just need to use a  matrix container
    Use EmployeeCode and BranchCode for row group
    ProblemCode as column group and SUM([No Of Problems]) as the data expression and it will generate the columns for you based on ProblemCode values automatically.
    See an example here
    Sample Matrix
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Error when uploading a crystal report with dynamic parameter into Infoview

    Hi All,
    I was trying to upload a crystal report which has a dynamic parameter into a Infoview. It shows an error message that say:- "Failed to read data from report file C:\WINDOWS\TEMP\tmp27A.rpt. Reason: Failed to read parameter object ". Can anybody help me in solving this?
    Thanks!
    Edited by: undefined on Aug 20, 2009 8:57 PM

    Post your question to the Business Objects Forum

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

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

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

Maybe you are looking for