How to make dynamic query using DBMS_SQL variable column names

First of all i will show a working example of what i intend to do with "EXECUTE IMMEDIATE":
(EXECUTE IMMEDIATE has 32654 Bytes limit, which isn't enough for me so i'm exploring other methods such as DBMS_SQL)
-------------------------------------------------CODE-----------------------------------
create or replace PROCEDURE get_dinamic_query_content
(query_sql IN VARCHAR2, --any valid sql query ('SELECT name, age FROM table') 
list_fields IN VARCHAR2) --list of the columns name belonging to the query (  arr_list(1):='name';   arr_list(2):='age';
-- FOR k IN 1..arr_list.count LOOP
-- list_fields := list_fields || '||content.'||arr_list(k)||'||'||'''~cs~'''; )
AS
sql_stmt varchar (30000);
BEGIN
               sql_stmt :=
'DECLARE
     counter NUMBER:=0;     
auxcontent VARCHAR2(30000);     
     CURSOR content_cursor IS '|| query_sql ||';
     content content_cursor%rowtype;     
     Begin
          open content_cursor;
          loop
               fetch content_cursor into content;
               exit when content_cursor%notfound;
               begin                              
                    auxcontent := auxcontent || '||list_fields||';                    
               end;
               counter:=counter+1;     
          end loop;
          close content_cursor;
          htp.prn(auxcontent);
     END;';
EXECUTE IMMEDIATE sql_stmt;
END;
-------------------------------------------------CODE-----------------------------------
I'm attepting to use DBMS_SQL to perform similar instructions.
Is it possible?

Hi Pedro
You need to use DBMS_SQL here because you don't know how many columns your query is going to have before runtime. There are functions in DBMS_SQL to get information about the columns in your query - all this does is get the name.
SQL> CREATE OR REPLACE PROCEDURE get_query_cols(query_in IN VARCHAR2) AS
2 cur PLS_INTEGER;
3 numcols NUMBER;
4 col_desc_table dbms_sql.desc_tab;
5 BEGIN
6 cur := dbms_sql.open_cursor;
7 dbms_sql.parse(cur
8 ,query_in
9 ,dbms_sql.native);
10 dbms_sql.describe_columns(cur
11 ,numcols
12 ,col_desc_table);
13 FOR ix IN col_desc_table.FIRST .. col_desc_table.LAST LOOP
14 dbms_output.put_line('Column ' || ix || ' is ' ||
15 col_desc_table(ix).col_name);
16 END LOOP;
17 dbms_sql.close_cursor(cur);
18 END;
19 /
Procedure created.
SQL> exec get_query_cols('SELECT * FROM DUAL');
Column 1 is DUMMY
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT table_name, num_rows FROM user_tables');
Column 1 is TABLE_NAME
Column 2 is NUM_ROWS
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT column_name, data_type, low_value, high_value FROM user_tab_cols');
Column 1 is COLUMN_NAME
Column 2 is DATA_TYPE
Column 3 is LOW_VALUE
Column 4 is HIGH_VALUE
PL/SQL procedure successfully completed.I've just written this as a procedure that prints out the column names using dbms_output - I guess you're going to do something different with the result - maybe returning a collection, which you'll then parse through in Apex and print the output on the screen - this is just to illustrate the use of dbms_sql.
best regards
Andrew
UK

Similar Messages

  • How to feed a query using a variable defined as Replacement Path-Query

    Scenario description : BI NetW 2004S - InfoCube with the following characteristics Customer, OrderDate, OrderYear and the following KeyFigure Number of Pieces.
    Objective: I need a query "QB" that shows how many pieces a set of customers has ordered in the year 2008. The set of customers is defined as all customers that in the previous years (the user can select one or more years) have ordered more than 500 pieces within the same year.
    Implementation: In general terms the idea is to build a query "QB" with the characteristic "Customer"  that is restricted (filtered) using a variable that is fed by another query "QA" (Replacement Path-Query).
    In order to have the selection of customers that for each of previous years (2007, 2006, 2005,...) have ordered more than 500 pieces, in the query "QA":
    - I put OrderYear as filter and defined a variable in order to ask the user which year/s he wants to analyse to define the selection
    - I put Customer and OrderYear in row
    - I put the KeyFigure Number of Pieces in column
    - I've defined the following condition: Number of Pieces > 500 with the option Caracteristic Assignment = All Characteristics in the Drilldown Indipendently
    Now if I run the query "QA" it works correctly showing me all customers that in the selected years have ordered more than 500 pieces within of the same year.
    If I run the query "QB" it shows a correct result only if I enter only one year (for example 2006) in the OrderYear field (coming from the query "QA"); if I enter more than one year (for example 2006 and 2007) the selection of customers showed is not the same defined by the first query "QB": I was expecting to see all customers defined from the first query less all customers that have no ordered any piece in 2008.
    Questions
    1) Why is query "QA" working on a different selection of customers when the user selects more than one year?
    2) Cosidering the scenario and the objective described above do you have any other idea?
    Thanks
    Ciao
    Roberto

    Hi Christophe,
         it's ok for me if I consider the customer only once in the final selection of customers that feeds the final query, this is my objective.
    However as test I've created 2 "input" queries, one related to 2006 and one related to 2007, and then in my destination query I've tried to restrict the customer using 2 variables of type replacement path-query (one attached to the 2006 query and one attached to the 2007 query). Unfortunately when I try to check and save the destination query, Query Designer tells me it is not possible to restrict the characteristic in this way.
    Could you please describe me steps you run in to order to restrict a characteristic using more than one variable of type replacement path-query?
    Thank you in advance for your answer.
    Ciao,
    Roberto

  • How to make dynamic actions using Set Value work in all browsers?

    I’m having a cross-browser incompatibility issue with dynamic actions using Set Value.  The dynamic action works like a charm on Chrome but has no effect on either IE or Firefox.  The code in oracle.apex.com and here are the credentials:
    Workspace: DDBA
    Username: [email protected]
    Password: redtruck12
    These code is on page 3 and here are the details:
    There are two report lists (Standard and Special) and some of the reports require additional information supplied in either select lists or text boxes.
    If the user selects a Standard report requiring a select list/text box, then the dynamic action sets the value of Special Reports to NULL (and vice-versa).
    The dynamic action is to prevent a simultaneous selection of both the Standard and Special reports.  To see how it works on Chrome, do this:
    Run Page 3
    Select the ‘Report for Search Criteria’ option from the Standard Report list.  A ‘Search Criteria’ text box appears
    Select the ‘Report by Release’ option from the Special Reports list.  A select list appears and the ‘Search Criteria’ text box disappears.
    If you do the same things on IE or Firefox, the text box does not disappear. 

    Hi,
    Things are going wrong with setting the item values to NULL. If you check your session state, you'll see that in chrome your items values indeed will be set to null, but in firefox they won't.
    Also I've noticed that you don't reset the other input fields, so their values persist in the session state. Since you submit your page every time you change one of the report select lists, this might lead to unexpected behaviour. Lastly, I've noticed you use a sql exists expression to manage the display/hide of your page items. A condition of type "Value of  expression 1 = expression 2" causes less overhead as you don't need to switch to the db sql engine for every item to validate.
    I'd suggest you rethink your specs and try to create:
    - One dynamic action (since a value of standard select excludes the value of special select, and vice versa)
    - Set the values for hidden items to null, also in session state
    - Use a refresh of region as extra event in your dynamic action, instead of submitting your page for every change.
    Regards,
    Vincent
    http://vincentdeelen.blogspot.com

  • How to create dynamic connection string with variables using ssis.

    Hello,
    Can anyone let me know on how to create dynamic connection string with variables using ssis?
    Any help would be appreciated.

    Hi vinay9738,
    According to your description, you want to connect multiple database from multiple servers using dynamic connection.
    If in this case, we can create a Table in our local database (whatever DB we want) and load all the connection strings.  We can use Execute SQL Task to query all the connection strings and store the result-set in a variable of object type in SSIS package.
    Then use ForEach Loop container to shred the content of the object variable and iterate through each of the connection strings. And then Place an Execute SQL task inside ForEach Loop container with the SQL statements we have to run in all the DB instances. 
    For more details, please refer to the following blog:
    http://sql-developers.blogspot.kr/2010/07/dynamic-database-connection-using-ssis.html
    If there are any other questions, please feel free to let me know.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • How do I...Mimic Replacement Path with Query using Customer Variable Exits?

    Hello SDN:
    We are on BW 3.5 SP16.
    We are currently using a replacement path Query(RP) with variables
    to populate a variable in another Query(T).
    The problem we are having is with performance.
    The entry of variables in replacement path Query(RP) is optional (This is necessary there cannot be required values)
    When results from Replacement Path Query are small performance is fine. (e.g. 10 seconds)
    When results from Replacement path query are large performance suffers. (e.g. 1+ minutes)
    Users are free to leave the replacement path variables empty resulting in a large set of data to be replaced. This is the worst performance case.
    We would like to discover a way to conditionally execute the replacement path query. That is if users do not enter values for the replacement Query(RP) variables do not execute the replacement path query(RP).
    Does anyone know if this is possible within reason and in customer exit space?
    We have reviewed the situation from all angles and the requirement for the replacement path FUNCTIONALITY and the freedom for the user to leave variable values blank remains.
    I've been searching and reading SDN and SAP notes for about a week and do not find threads which address this situation.
    We are also exploring Customer variable exits to mimic replacement path functionality
    (different topic subject="How do I...Mimic Replacement Path with Query using Customer Variable Exits?")
    Any help will be appreciated
    Many thanks
    David Schuh

    My appologies-I posted this message with the wrong subject. I will repost it with appropriate subject.
    dave schuh

  • How to make dynamic search items in a report?

    Hi all,
    I have two questions.
    1. How to make dynamic search (i.e without GO button) field above report to provide dynamic search by words in one field of report query?
    2. How to make similar multiply dynamic search fields on report to provide individual search by selected fields of report with refine capability (i.e any search conditions in different fields must work together as complex WHERE clause)
    Thanks in advance

    hey yuri--
    if i'm understanding your questions correctly, the easiest way to achieve the functionality you're after is to have your query criteria fields submit the page when values are entered/selected. the page should then branch back to itself using the submitted criteria in the query. because you're asking about dynamically adding in your where clause predicates, you should consider using a report region of type "SQL Query (Pl/sql Function Body Returning SQL Query)". that way you can use pl/sql to piece together your query based on the provided criteria.
    so the part of your question i'm not sure of is when your page should submit itself ("without a GO button" as you said). for your first question, it seems to be a simple matter of javascript. you want users to be able to enter search criteria into a field and have that criteria be using in the report. to facilitate that we have a few self-submitting item types such as "SelectList with Submit" and "Text Field (always submits page when Enter pressed)". for your second question, it seems that you should have a Go button for the user to indicate he's done entering in his query criteria. anyhow, that's up to you, i suppose. hopefully this response will give you the concepts you need to implement this as you'd like.
    regards,
    raj
    ps-after re-reading your post, i now realize there's a chance that you wanted users to not have to submit the page at all when filtering their result sets. if that's the case, you'd have to use javascript for that cumbersome feat. google would be a good place to go for that code.

  • How can I make my query to compare only columns of two tables... not the storage information?

    11GR2
    =-----------------------------------
    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    begin
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'PRETTY', TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SQLTERMINATOR',TRUE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'SEGMENT_ATTRIBUTES', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE', FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'TABLESPACE',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'REF_CONSTRAINTS',FALSE);
    DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'CONSTRAINTS_AS_ALTER',FALSE);
    End;
    select REGEXP_REPLACE(dbms_metadata_diff.compare_alter('TABLE','TABLE_NAME_A','TABLE_NAME_A','USER1','USER2'),('USER1...'),'', 1, 0, 'i') from dual

    I am using below querry to compare two table that has same name, under two different users... But after making storage information false like below and  if the storage information is different on column level than it create "Alter modify " statements for the column ... How can I make my query to compare only columns of two tables... not the storage information?
    If you want help you have to SHOW us what you are doing and how you are doing it; you can't just try to tell us in your own words.
    We can't see your computer screen.

  • How to make Dynamically Shortened Text With "Show More"

    Hi there! i want to know how to make dynamically shortened text with show more or read more in my website using HTML 5 pages  or ASP.NET ?
    example like these paragraphs 
    Lorem Ipsum är en utfyllnadstext från tryck- och förlagsindustrin. Lorem ipsum har varit standard ända sedan 1500-talet, när en okänd boksättare tog att antal bokstäver och blandade dem för att göra ett provexemplar av en bok. Lorem ipsum har inte bara överlevt fem århundraden, utan även övergången till elektronisk typografi utan större förändringar. Det blev allmänt känt på 1960-talet i samband med lanseringen av Letraset-ark med avsnitt av Lorem Ipsum, och senare med mjukvaror som Aldus PageMaker.
    Det är ett välkänt faktum att läsare distraheras av läsbar text på en sida när man skall studera layouten. Poängen med Lorem Ipsum är att det ger ett normalt ordflöde, till skillnad från "Text här, Text här", och ger intryck av att vara läsbar text. Många publiseringprogram och webbutvecklare använder Lorem Ipsum som test-text, och en sökning efter "Lorem Ipsum" avslöjar många webbsidor under uteckling. Olika versioner har dykt upp under åren, ibland av olyckshändelse, ibland med flit (mer eller mindre humoristiska).
    I motsättning till vad många tror, är inte Lorem Ipsum slumvisa ord. Det har sina rötter i ett stycke klassiskt litteratur på latin från 45 år före år 0, och är alltså över 2000 år gammalt. Richard McClintock, en professor i latin på Hampden-Sydney College i Virginia, översatte ett av de mer ovanliga orden, consectetur, från ett stycke Lorem Ipsum och fann dess ursprung genom att studera användningen av dessa ord i klassisk litteratur. Lorem Ipsum kommer från styckena 1.10.32 och 1.10.33 av "de Finibus Bonorum et Malorum" (Ytterligheterna av ont och gott) av Cicero, skriven 45 före år 0. Boken är en avhandling i teorier om etik, och var väldigt populär under renäsanssen. Den inledande meningen i Lorem Ipsum, "Lorem Ipsum dolor sit amet...", kommer från stycke 1.10.32.
    Den ursprungliga Lorem Ipsum-texten från 1500-talet är återgiven nedan för de intresserade. Styckena 1.10.32 och 1.10.33 från "de Finibus Bonorum et Malorum" av Cicero hittar du också i deras originala form, åtföljda av de engelska översättningarna av H. Rackham från 1914.

    Moved to the main Dreamweaver support forum.
    There are several ways you could approach this. Here's one you might try:
    Give the first paragraph an ID, such as "first", and wrap the paragraphs you want to hide in a <div> with another ID, such as "more". Then add the following block of JavaScript just before the closing </body> tag of the page:
    <script>
    var first = document.getElementById('first'),
         more = document.getElementById('more'),
         trigger = document.createElement('span');
    trigger.id = 'trigger';
    trigger.innerHTML = 'Show less';
    first.appendChild(trigger);
    function toggleDiv() {
      var state = more.className,
           text = trigger.innerHTML;
      more.className = (state == 'open') ? 'closed' : 'open';
      trigger.innerHTML = (text == 'Show more') ? 'Show less' : 'Show more';
    toggleDiv();
    if (trigger.addEventListener) {
        trigger.addEventListener('click', toggleDiv, false);
    } else if (trigger.attachEvent) {
      trigger.attachEvent('onclick', toggleDiv);
    } else {
      trigger.onclick = toggleDiv;
    </script>
    This gets references to the "first" paragraph and the "more" <div>. It also creates a <span> with the ID "trigger" that's appended to the "first" paragraph. The rest of the script defines a function called toggleDiv(), which toggles the "more" <div> open and closed, and changes the text in the "trigger" <span>.
    You also need to create the following style rules for the various elements:
    <style>
    #trigger {
        text-decoration: underline;
        color: blue;
        cursor: pointer;
    #more {
        transition: ease-out .7s;
        overflow: hidden;
    #more p:first-child {
        margin-top: 0;
    #more.closed {
        height: 0;
        -webkit-transform: translateY(-600px);
        transform: translateY(-600px);
    #more.open {
        -webkit-transform: translateY(0);
        transform: translateY(0);
        max-height: 600px;
    #more + p {
        margin-top: 0;
    </style>
    This solution hides the text and creates the "trigger" <span> only if JavaScript is enabled in the browser. It should work in all browsers, including Internet Explorer 8 and earlier.

  • How to make load simulator using labview 2010

    i want to ask how to make load simulator using labview? 
    Solved!
    Go to Solution.

    what have you tried so far? and exactly what is it your tying to do?
    Please remember to accept any solutions and give kudos, Thanks
    LV 8.6.1, LV2010,LV2011SP1, FPGA, Win7

  • How to make RC circuit using labview

    Hi,
    how to make RC circuit using labview... Thx

    Your question seems awfully similar to this thread. Is this a school assignment?
    Jeff
    Using Labview 7 Express

  • How to enable dynamic query in weblogic 7.0?

     

    Hi,
    The documentation explains how to enable dynamic queries and set a
    method-permission to control access. If you find the information at the
    following link insufficient, let me know.
    http://e-docs.bea.com/wls/docs70/ejb/cmp.html#1089703
    You enable dynamic queries in your weblogic-ejb-jar.xml file with the following:
    <enable-dynamic-queries>True</enable-dynamic-queries>
    You can set a method permission as follows:
    <security-role>
    <role-name>Admin</role-name>
    </security-role>
    <method-permission>
    <role-name> Admin </role-name>
    <method>
    <ejb-name> EmployeeEJB </ejb-name>
    <method-name> createQuery </method-name>
    </method>
    </method-permission>
    - Matt
    Sanjeev Chopra wrote:
    also posting to EJB newsgroup
    "CottonXu" <[email protected]> wrote in message
    news:[email protected]..
    How to enable dynamic query in weblogic 7.0? The documentation accompanieswith
    Bea doesn't explain it in detail. How to set <method-permission> inejb-jar.xml?
    Thanks in advance.

  • About how to build dynamic maps using jdeveloper 10g and mapviewer

    i follow the guidance (about how to build dynamic maps using jdeveloper 10g and oracle application server mapviewer) to write a jsp file,but error take palce ,i get information "Project: D:\jdev1012\jdev\mywork\WebMap\ViewController\ViewController.jpr
    D:\jdev1012\jdev\mywork\WebMap\ViewController\public_html\WebMap.jsp
    Error(12,37): cannot access class oracle.lbs.mapclient.taglib.MapViewerInitTag; file oracle\lbs\mapclient\taglib\MapViewerInitTag.class not found
    Error(12,190): cannot access class oracle.lbs.mapclient.taglib.MapViewerInitTag; file oracle\lbs\mapclient\taglib\MapViewerInitTag.class not found
    Error(12,102): cannot access class oracle.lbs.mapclient.taglib.MapViewerInitTag; file oracle\lbs\mapclient\taglib\MapViewerInitTag.class not found
    Error(12,28): cannot access class oracle.lbs.mapclient.MapViewer; file oracle\lbs\mapclient\MapViewer.class not found
    Error(12,40): cannot access class oracle.lbs.mapclient.MapViewer; file oracle\lbs\mapclient\MapViewer.class not found
    Error(13,37): cannot access class oracle.lbs.mapclient.taglib.MapViewerSetParamTag; file oracle\lbs\mapclient\taglib\MapViewerSetParamTag.class not found
    Error(13,198): cannot access class oracle.lbs.mapclient.taglib.MapViewerSetParamTag; file oracle\lbs\mapclient\taglib\MapViewerSetParamTag.class not found
    Error(13,106): cannot access class oracle.lbs.mapclient.taglib.MapViewerSetParamTag; file oracle\lbs\mapclient\taglib\MapViewerSetParamTag.class not found
    Error(14,37): cannot access class oracle.lbs.mapclient.taglib.MapViewerRunTag; file oracle\lbs\mapclient\taglib\MapViewerRunTag.class not found
    Error(14,188): cannot access class oracle.lbs.mapclient.taglib.MapViewerRunTag; file oracle\lbs\mapclient\taglib\MapViewerRunTag.class not found
    Error(14,101): cannot access class oracle.lbs.mapclient.taglib.MapViewerRunTag; file oracle\lbs\mapclient\taglib\MapViewerRunTag.class not found
    Error(15,37): cannot access class oracle.lbs.mapclient.taglib.MapViewerGetMapURLTag; file oracle\lbs\mapclient\taglib\MapViewerGetMapURLTag.class not found
    Error(15,200): cannot access class oracle.lbs.mapclient.taglib.MapViewerGetMapURLTag; file oracle\lbs\mapclient\taglib\MapViewerGetMapURLTag.class not found
    Error(15,107): cannot access class oracle.lbs.mapclient.taglib.MapViewerGetMapURLTag; file oracle\lbs\mapclient\taglib\MapViewerGetMapURLTag.class not found"
    can you help?
    greetings

    I found a lot of information in document 133682.1 on metalink.
    step by step example how to deploy a JSP business component application.

  • Can someone help me in learning how to make business cards using pages

    can someone please help me in learning how to make business cards using pages

    You could jump start the process with an Avery MS Word 8-up business card template as a free download. Either version of Pages will digest it nicely. Once you load it into Pages, do a File > Save As Template.. , add it to Chooser, and give it your name choice. Both versions of Pages will remove the printer registration marks in all four template corners. The free LibreOffice Writer retains them.

  • How to make af: query (ResultComponentId) has two target values?

    hello all :D
    i'm newbie in jdev, i have little problem with af:query.
    how to make af: query (ResultComponentId) has two target values?
    thx
    agungdmt :D

    I think you can simply set the second target control's partialTrigger to the af:query.
    and access to the same binding attribute as your first target. (e.g.: if you have 2 target tables, set the value to #{bindings.XxxxxVO1.collectionModel})
    Samson Fu

  • How to make a query to list out Journal voucher that hasn't been posted

    Hi, do you know how to make a query to list out Journal voucher that hasn't been posted?
    By what code name identify that?
    Thanks.
    Raymond
    Edited by: Rui Pereira on Aug 6, 2008 3:57 PM

    jack,
    there is no link with OBTD to OJDT and JDT1.
    voucher number in obdt is different,
    after posting voucher is saved as journal entry seperate
    number is generated.
    you can link OACT,OCRD WITH OJDT,JDT1.
    Jeyakanthan

Maybe you are looking for