Dynamic column names in Oracle

HI SOS!! calling for help...
i am trying to query the following. I want to remove the duplicates in the ID, and combine them into one... While doing so, I want to keep the data as it is by creating dynamic columns reason_1, reason_2, reason_3 with their corresponding TIME. In case of same reasons, I want to add the TIME. The database is as follows:
ID     REASON     TIME
A     41A..........     27
A     93K..........16
B     89C...........3
B     93K...........7
B     48C..........     4
C     93K..........     24
C     93K..........     7
C     48C.........10
Expected Result is
ID     REASON_1......TIME_1.... REASON_2...TIME_2....REASON_3.........TIME_3
A........ 41A............ 27........... 93K............16          
B........ 89C............ 3............ 93K............7...........48C.................. 4
C........ 93K........... 31.......... 48C..............10          
Would be grateful if someone could try helping me out of this as early as possible.
Edited by: 968125 on Oct 28, 2012 11:01 PM

You still haven't made it clear what the requirement is.
Is there a maximum number of reasons that can occur per ID? If so, you can code the pivoting of your data with something like:
SQL> ed
Wrote file afiedt.buf
  1  with t as (select 'A' as ID, '41A' as reason, 27 as time from dual union all
  2             select 'A', '93K', 16 from dual union all
  3             select 'B', '89C', 3 from dual union all
  4             select 'B', '93K', 7 from dual union all
  5             select 'B', '48C', 4 from dual union all
  6             select 'C', '93K', 24 from dual union all
  7             select 'C', '93K', 7 from dual union all
  8             select 'C', '48C', 10 from dual)
  9  --
10  -- END OF TEST DATA TABLE SIMULATED USING 'WITH' CLAUSE
11  -- SIMPLY USE THE SELECT STATEMENT BELOW ON YOUR OWN TABLE
12  --
13  select id
14        ,max(decode(rn,1,reason)) as reason_1
15        ,max(decode(rn,1,time)) as time_1
16        ,max(decode(rn,2,reason)) as reason_2
17        ,max(decode(rn,2,time)) as time_2
18        ,max(decode(rn,3,reason)) as reason_3
19        ,max(decode(rn,3,time)) as time_3
20        ,max(decode(rn,4,reason)) as reason_4
21        ,max(decode(rn,4,time)) as time_4
22        ,max(decode(rn,5,reason)) as reason_5
23        ,max(decode(rn,5,time)) as time_5
24  from (/* assign some row numbers within each ID, ordering by 'reason' then 'time' */
25        select id, reason, time
26              ,row_number() over (partition by id order by reason, time) as rn
27        from   t
28       )
29* group by id
SQL> /
I REA     TIME_1 REA     TIME_2 REA     TIME_3 REA     TIME_4 REA     TIME_5
A 41A         27 93K         16
B 48C          4 89C          3 93K          7
C 48C         10 93K          7 93K         24In this example, it will cater for up to 5 reasons/times per ID... and you can code for more if you need very easily.
Also, as you're using 11g, you can use the new PIVOT query, for which you can find plenty of examples if you google or search these forums, or follow the FAQ link.
If you don't have any idea how many reasons there could be, then you really are looking at generating columns dynamically.
The problem with that is, because Oracle needs to know the SQL projection (see the FAQ link already provided), it has to know how many columns are going to be returned from a query before any data is fetched... but you are saying that the columns returned have to be based on the data itself. To do that you have two main options:
1) You query the data once to determine how many columns you are going to need and then dynamically build up a query in PL/SQL code with the right number of columns (or use one of the other dynamic methods shown in the FAQ)
or
2) You step back and ask yourself if SQL is really the best place to be trying to produce this output. Reporting tools are often better suited to this requirement as they are made to query the data back from a database and then pivot and layout the data based on the data returned.

Similar Messages

  • Dynamic column name for Oracle Server Procedure

    hello,
    May be it's not a right place for my question, but I hope that some of you can help me.
    I have source table A that has data of the same kind in 62 fields, let's say employee count for 62 departments. I do some processing with these counts(sum(emp_count) of the same departments for different locations) and store these counts in the variables EC1, EC2, EC3 .. EC62.
    Then I need to insert them into my table that has very simple structure let's say table B (dept_no Number(3),
    emp_count Number(6))
    I want to do a loop and use dynamic colunm EMP_COUNT, something like this:
    FOR k in 1..62 LOOP
    EMP_COUNT := 'EC'| |k;
    IF EMP_COUNT <> O THEN
    insert into B
    VALUES ( K , EMP_COUNT);
    END IF;
    END LOOP;
    I understand that I need to take a Value of my dynamic colunm EMP_COUNT. Is it possible to do in Oracle Server Procedure? Any idea?
    Any help will be apreciated.
    null

    After having worked in other environments where you can manipulate data records with postitional parameters, Oracle can be frustrating because it demands the explicit use of field names in DML/Select statements. A way around this is to use DBMS_SQL or Dynamic Sql. I have used DBMS_SQL to create and execute dynamic statements with great success. Since you are creating, compiling, and running a dynamic block every time you execute your procedure, this is not recommended except in the rare instances when there is no better way around it.
    Oracle8i introduces native dynamic SQL, an alternative to DBMS_SQL. Using native dynamic SQL, you can place dynamic SQL statements directly into PL/SQL blocks.
    In most situations, native dynamic SQL can replace DBMS_SQL. Native dynamic SQL is easier to use and performs better than DBMS_SQL.
    Example of Dynamic SQL<------------------------
    BEGIN
    -- bulk fetch the list of office locations
    SELECT location BULK COLLECT INTO loc_array
    FROM offices;
    -- for each location, give a raise to employees with the given 'job'
    FOR i IN loc_array.first..loc_array.last LOOP
    dml_str := 'UPDATE emp_' &#0124; &#0124; loc_array(i)
    &#0124; &#0124; ' SET sal = sal * (1+(:raise_percent/100))'
    &#0124; &#0124; ' WHERE job = :job_title';
    EXECUTE IMMEDIATE dml_str USING raise_percent, job;
    END LOOP;
    Look for more information on dynamic SQL by
    searching for DBMS_SQL.
    Good Luck
    null

  • Dynamic column name sql?

    I need to do a select statement using dynamic column names. Can it be done WITHOUT building a string to execute the sql?
    In other words, I want to use a variable name in the SELECT part of a statement.
    Thanks

    Properly done, there shouldn't be a great difference in the performance of static and dynamic SQL. Of course, dynamic SQL is a whole lot more complicated to get right. It's also rather at odds with your requirement that column names get passed in dynamically-- if you don't know what columns you're going to select at compile time, you can't use static SQL.
    That said, there are a handful of tricks around using Oracle's built-in XML processing functionality to simulate dynamic SQL. This is almost certainly less efficient than doing dynamic SQL in your case, and a whole lot more complicated, but it's technically not dynamic SQL.
    The proper response, though, is almost certainly to either
    1) figure out how to design the application so that column names need not be passed in at runtime or
    2) use dynamic SQL.
    If at all possible, option 1 is generally preferable. While there are situations where dynamic SQL is necessary, those tend to be rather rare.
    Justin

  • How to change recordset bahaviour to accept dynamic column names in the where clause

    Hi
    im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
    "select id,name from mytable where $tablename-$myvar";
    but when i do this my i break the recordset and it disappear
    and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
    and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
    so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
    thanks in advance.

    As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
    Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
    // create array of acceptable values
    $valid = array('column_name1', 'column_name2', 'column_name3');
    // if the query string contains an acceptable column name, use it
    if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
      $col = $GET['colname'];
    } else {
      // set a default value if the submitted one was invalid
      $col = 'column_name1'
    You can then use $col directly in the SQL query.

  • Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

    Im getting an error when running a procedure that includes this code.
    I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
    DECLARE @retval AS DECIMAL(12,2)
    DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
    DECLARE @sqlcmd AS NVARCHAR(150)
    DECLARE @paramdef NVARCHAR(150)
    SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
    SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
    SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
    SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
    --default
    SET @retval = 0.0;
    EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
    SELECT @retval
    DECLARE @return_value DECIMAL(12,2)
    EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
    @SpreadKey = 1,
    @MonthNumber = 4
    SELECT 'Return Value' = @return_value
    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to numeric.

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
    This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
    the shoe size, the phone number or something else at run time of this entity. 
    In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point. 
    Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity. 
    Do you know that SQL is a declarative language? This family of languages does not use local variables! 
    Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.  
    Think about how silly this is: 
     SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
    We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental. 
    We need to see the DDL so we can re-write this mess. Want to fix it or not?
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to rename the column name in oracle 8i?

    hi,
    Does anyone know how to rename the column name in oracle 8i?My method was drop the relationship key first then delete the old column,finally add the new column.
    Thanks for your replay.
    jing

    There is no facilty to rename a column name in Oracle 8i. This is possible from Oracle 9.2 version onwards.
    For you task one example given below.
    Example:-
    Already existed table is ITEMS
    columns in ITEMS are ITID, ITEMNAME.
    But instead of ITID I want ITEMID.
    Solution:-
    step 1 :- create table items_dup
    as select itid itemid, itemname from items;
    step 2 :- drop table items;
    step 3 :- rename items_dup to items;
    Result:-
    ITEMS table contains columns ITEMID, ITEMNAME

  • 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);

  • Dynamic column name in OBIEE

    Hi all,
    In my report i need to show one chart view. I'm having one prompt. There the user is asked to select a no. for eg. say 10. and a date eg. 10-JAN-09. So my report should show the data from 10-JAN-09 and go backwards to 10 days. if he selects 5 days then only 5 days of data only need to show from that date. This part is ok. The chart has five sections in it. They are
    1) 80-100% of the time period
    2) 60-80%
    3) 40-60%
    4) 20-40%
    5) <20%
    So the legends should vary according to this.
    Suppose if the user selects 10 days then the legend should be,
    1) 8-10 days
    2) 6-7 days
    3) 4-5 days
    4) 2-3 days
    5) less than 2 days
    If user selects 5 means then the legend should be,
    1) 5 days
    2) 4 days
    3) 3 days
    4) 2 days
    5) 1 day
    In the prompt im saving this value in one variable. So all i need to do is to apply aggregation on the variable and place it in the column name. But i dont know where to give it. Please help.
    Thanks,
    Karthick

    Hi when you dynamically change the table column that will automatically reflect in the chart legend.
    please check the following link for dynamically changing column header name
    http://oraclebizint.wordpress.com/2008/01/25/oracle-bi-ee-101332-dynamic-column-headers-using-presentation-variables-sets-and-conditional-formatting/

  • Dynamic Column Names in Flat File Destination

    Hello,
    Inside a Data Flow Task, I have an ADO.Net data source which executes a stored procedure that provides results in 5 columns.
    The requirement is to have it connect to a flat file destination, such that the column names is dependent on what data was pulled by the data source. There is a variable indicator which identifies the data that was pulled. For example:
    If the indicator is 0, then the columns names will be A,B,C,D,E. Otherwise, if the indicator is 1, then column names will be V,W,X,Y,Z.
    Any suggestions will be of great help.
    AJ

    If you only have two variations then use a branched execution (based on precedence constraints) and direct it to one DFT or another based on the result returned by the stored procedure.
    Otherwise use .net
    code to create one package or another dynamically.
    PS: I suggest not to bother using SSIS for such a simplistic scenario.
    Arthur My Blog

  • Dynamic column names

    I created a line chart with the following sql statement:
    select null link, periode_jaar, sum(totaal) total from V_KPL_VZ_OWB@rapportage_dwhtest
    where periode_jaar = (Select max(periode_jaar) from V_KPL_VZ_OWB@rapportage_dwhtest)
    group by periode_jaar
    order by periode_jaar
    In the legend of the chart the line is named total. I would like have it named for example: Total 2009
    So how i create the dynamic column? Any ideas? Tnx in advnaced

    tnx for helping, i posted my xml code below where to put the tag: <format>{%Name} ({%Value})</format>
    i assume i have to replace %Name with my sirie name and the %Value with the name i wanted?
    Is it possible to replace %Value with an item like :p1_year
    &#60;?xml version = "1.0" encoding="utf-8" standalone = "yes"?&#62;
    &#60;root&#62;
    &#60;type&#62;
    &#60;chart type="2DLine"&#62;
    &#60;animation enabled="yes" appearance="size" speed="10" /&#62;
    &#60;hints auto_size="yes"&#62;
    &#60;text&#62;&#60;![CDATA[{NAME}, {VALUE}]]&#62;&#60;/text&#62;
    &#60;font type="Verdana" size="10" color="0x000000" /&#62;
    &#60;/hints&#62;
    &#60;names show="yes" width="150" placement="chart" position="bottom" &#62;
    &#60;font type="Verdana" size="10" color="0x000000" /&#62;
    &#60;/names&#62;
    &#60;values show="no" prefix="" postfix="%" decimal_separator="," decimal_places="0" /&#62;
    &#60;arguments show="no" /&#62;
    &#60;line_chart left_space="5" right_space="5"&#62;
    &#60;block_names enabled="no" /&#62;
    &#60;/line_chart&#62;
    &#60;/chart&#62;
    &#60;workspace&#62;
    &#60;background enabled="yes" type="solid" color="0xffffff" alpha="0" /&#62;
    &#60;base_area enabled="no" /&#62;
    &#60;chart_area enabled="yes" x="80" y="50" width="380" height="280" deep="0"&#62;
    &#60;background enabled="no"/&#62;
    &#60;border enabled="yes" size="1"/&#62;
    &#60;/chart_area&#62;
    &#60;x_axis name="Jaar" smart="yes" position="center_bottom" &#62;
    &#60;font type="Verdana" size="14" color="0x000000" bold="no" align="center" /&#62;
    &#60;/x_axis&#62;
    &#60;y_axis name="%" smart="yes" position="left_center" &#62;
    &#60;font type="Verdana" size="14" color="0x000000" bold="no" align="center" /&#62;
    &#60;/y_axis&#62;
    &#60;grid&#62;
    &#60;values /&#62;
    &#60;/grid&#62;
    &#60;/workspace&#62;
    &#60;legend enabled="yes" x="480" y="50"&#62;
    &#60;font type="Verdana" size="10" color="0x000000" /&#62;
    &#60;/names&#62;
    &#60;values enabled="YES"/&#62;
    &#60;scroller enabled="no"/&#62;
    &#60;header enabled="no"/&#62;
    &#60;background alpha="0"/&#62;
    &#60;/legend&#62;
    &#60;/type&#62;
    #DATA#
    &#60;/root&#62;

  • How do i change column names in oracle model?

    Hi,
    I am performing a migration from SQL SERVER 7.0 to Oracle 8.1.7.
    I have tables that have tables in SQL SERVER with column names
    that are "TYPE" and "BODY".(These are generally TEXT datatype
    columns that need to be converted to LONG in Oracle.We need
    these to be LONG datatype in Oracle because of an application we
    are using. LOBS cannot be allowed)
    The migration utility renames these columns as "TYPE_"
    and "BODY_" and creates the tables in the Oracle Database.
    I need to have these tables in Oracle with the same column names
    viz. "TYPE" and "BODY" .
    I can create new tables in Oracle with the column names "TYPE"
    and "BODY" but cannot change the options in the migration
    workbench for this.
    Is there any option or any workaround I can use to change the
    column names in the Oracle model?or set the options so that the
    Oracle model tables donot modify these column names?
    Thanks in advance for all the help.
    Mandar

    The words 'TYPE' and 'BODY' are reserved Oracle words. Its best
    to go along with what the workbench has suggested. If you have
    to keep the original names of the columns trying wrapping double
    quotes around them after the data migration is complete. This
    may cause a case sensitivity or referential problem later on
    though.

  • Dynamic Column name in a Cursor

    Hello there,
    How can I access data in cursor's field with dynamic fields names, more illustration follows:
    My table has columns named as C1,C2,C3 so on
    defined a cursor cursor_name on that table,
    I need to access the fields by a loop like this:
    OPEN cursor_name;
    Fetch cursor_name into rec;
    for i in 1 .. 10 loop
    if rec.ci = 1Then
    end if;
    end loop
    close cursor_name;
    where rec,ci represents the name of the cursor fields, so that I loop over them,
    how can I implement such an idea,
    thanks in advance
    regards

    Thanks Bily, and user10715047,
    actually the reason behind the need of such an approach, is as following:
    assume that I have table of set of logical conditions, " LOGICAL CONDITIONS" has three columns: ID, Condition_name and the logical_condition, example:
    1, c1,  x = 1
    5, c2,  y = 2
    10, c3, p = 3 where ID is just a sequence to identify the records from each other "primary key"
    assume that I need to provide the possible combination of the result of applying each of the conditions, for example :
    if c1 = 1 ,c2= 0 and c3= 1 then  my result must be 1 ' This according some predefined rulesso that I created table which contains all the possible logical conditions, ( as the max number of logical conditions are known)
    defined as follows : combination( combination_ID, c1, c2, c3, c4, ....cmax, result)
    sample record:
    combination_ID, c1,  c2, c3, .. c max, result
              100,   1,    0,   1, ....., 1, 1in the PL/SQL procedure, I would get all the needed combination, into a cursor, then to optimized the code, I need to access the fields ( which is the Ci) in a loop
    for i in 1..3 loop
    if cursor_rec.ci = 1 then
    Action
    end if;
    end loop;the dynamic name I meant in my first post was this : cursor_rec.ci ,
    so that I can access the cursor's fields without the need to name them one by one, as there could be long sequence of conditions to be checked.
    hope that I made the idea clearer, Any suggestions, please !
    anyway I will give the DBMS_SQL cursors a shot , try if I can use to implement the purpose,
    as I know similar dynamical variable names, is available in Java,
    Regards,

  • Dynamic forms using dynamic column names

    I have a table with columns such as level_1, level_2, etc.
    until level_11 and I have another table with level_id and
    description, i.e. for level with id = 1 the description could be
    'Crawl.' Id 2 could be 'Walk' etc.
    I'm trying to make a checklist so people can mark when
    they've done things on the checklist, and then upload those values
    to the appropriate tables to store the information so it's all
    still there when they go back to check off a new skill.
    I can't figure out how to make the column names in the form
    dynamic.
    I've played around with the formatting and still can't quite
    get it. I've tried evaluate(queryname.level_#level_id#),
    queryname.label, a bunch of other ones, and I can't seem to get it
    to work.
    Thanks for the help!

    Get to know CF's structure / array notation. This comes in
    very handy when dealing with queries and form fields.
    - Form.myFieldName can also be referenced by
    Form["myFieldName"]
    - MyQuery.myField can also be referenced by
    MyQuery["myField"][rowNumber]
    Anything in the above example surrounded by quotation makes
    can be made dynamic by just adding in a cf variable surrounded by
    pound signs:
    get_dealer_completion["level_#level_id#"][1]

  • Dynamic Column Names from one table and its corresponding values from another table

    I have 2 tables. First tables gives the specification if a column is required or not. we have the 2nd table with the same column name where we provide the actual values.
    I want to select all the required columns from the 1st table and retrieve the values for those from the 2nd table. Both this i want to achieve in a single select statement.

    This wil require a dynamic Query with a Pivot
    DECLARE @ColsPivot as VARCHAR(MAX);
    DECLARE @Query  AS VARCHAR(MAX);
    1. Retreive the ID for all required field
    SET @ColsPivot = (SELECT STUFF((SELECT  ',' + quotename(CAST([RequirementID] as varchar(3))) FROM [dbo].[Requirement] WHERE required=1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,''));
    This will give you : [1],[2],[3],[8],[9],[14] for exemple.
    2. Build your Query
    SET @Query ='SELECT ClientID,'+@ColsPivot+''
        FROM (
            SELECT [ClientID],[RequirementID],[Value]
            FROM dbo.RequirementValue
            WHERE ClientID=@CliendID --Optional SP parameter
        )src
              PIVOT(
                MAX(Value)
                for [RequirementID] in ('+@ColsPivot+')
        ) p';
    3. Exec(@Query);

  • Dynamic Column Names using Refcursors

    Hi,
    I have a stored procedure which returns a refcursor. The refcursor contains a SQL query in which the column names and number of columns vary dynamically based on the date parameters passed.
    "My objective is to return certain XYZ details of employees for a certain month range."
    For ex: For the month of Aug-2011, the column names would be '1-AUG-11' to '31-AUG-11 and for Feb-2011 '1-FEB-11' to '28-FEB-11'
    My issue is, when I execute the refcursor query using "EXEC", my column names/headings are preserved.
    FIELD NAMES: EMPLOYEE_CODE XYZ_TYPE *1-AUG-11* *2-AUG-11* ... *31-AUG-11*
    DATA: EMPCODE_Z TYPE1 VALUE_1 VALUE_1 ... VALUE_31
    Whereas when I fetch the refcursor into a collection of nested table and display, my column names are lost.
    DATA: EMPCODE_Z TYPE1 VALUE_1 VALUE_1 ... VALUE_31
    Is there a way where I can preserve the column names from the refcursor after fetching into pl/sql collections?
    Any help would be highly appreciated.
    Thank you.
    Edited by: 867622 on Nov 11, 2011 4:38 PM

    867622 wrote:
    If not dynamic SQL, how can the number of columns be altered based on the input parameters?Cannot. A dynamic SQL projection means dynamic SQL (there's an exception to this, and despite interesting is not relevant to 99.99% of problems dealing with dynamic SQL projections).
    You can however still use a dynamic projection and wrap that into a user defined type interface.
    Here's the basic approach:
    // create a user define type that will provide the wrapper for the SQL projection
    create or replace type TString as table of varchar2(4000);
    // build dynamic SQL projections via this type, e.g.
    select
      TStrings( object_id, object_name, created )
    from user_objects
    select
      TStrings( emp_id, dept_id, salary, commission )
    from employeesDespite the SQL cursors being different and the columns and number of columns being selected different, the SQL projection of both are the same. The Count method tells you the number of columns in the projection. Referencing an applicable column is simply done by using the column's sequential number in the projection.
    You also do not have to use a collection or varchar2 as the wrapper type - you can create complex user objects and use the collection type for that, as the SQL projection.
    Another alternative is converting the ref cursor into a DBMS_SQL cursor and using the latter's describe interface to dynamically determine the structure of the SQL projection and fetching the column values from it. But 11gr1 or later is needed for doing this.

Maybe you are looking for