Setting Column Names in Dynamic Pivot Query

Hi all,
I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
Workspace: MYHOSTACCT
Username : DEVUSER1
Password : MYDEVACCTAnd, here is my test application info:
ID     : 42804
Name   : dynamic query test
Page   : 1
Table 1: PROJECT_LIST         (Alias = PL...  Listing of Projects)
Table 2: FISCAL_YEAR          (Alias = FY...  Lookup table for Fiscal Years)
Table 3: PROJECT_FY           (Alias = PF...  Intersection table containing project fiscal years)
Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
Please let me know if you need anymore information, and many thanks in advance!
Mark

Hi Tony,
Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
DECLARE 
  v_query      VARCHAR2(4000);
  v_as         VARCHAR2(4);
  v_range_from NUMBER;
  v_range_to   NUMBER;         
BEGIN
  v_range_from := :P1_FY_FROM;
  v_range_to   := :P1_FY_TO;
  v_query      := 'SELECT ';
  -- build the dynamic column selections by looping through the fiscal year range.
  -- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
  FOR i IN v_range_from.. v_range_to  LOOP
    v_as    := 'FY' || SUBSTR(i, 3, 4);
    v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
      || v_as || ',';
  END LOOP;
  -- add the rest of the query to the dynamic column selection
  v_query := rtrim(v_query,',') || ' FROM ('
    || 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
    || 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
    || 'LEFT OUTER JOIN ('
    || 'SELECT FY_ID, PFH_HEADCOUNT '
    || 'FROM PROJECT_FY_HEADCOUNT '
    || 'JOIN PROJECT_FY USING (PF_ID) '
    || 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
    || 'ON A.FY_ID = B.FY_ID)';
  RETURN v_query;
END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
Thanks again!
Mark

Similar Messages

  • How to dynamically set column name in Answers

    Hi.
    How to dynamically set column name in Answers, for example I want to put presentation variable in column header. Is this possible?
    Regards,
    Goran Ocko
    http://108obiee.blogspot.com/

    May be a rude way .. but it works.
    Add narrative view and use Java script to change the column headings based on the variables.
    <script language="javascript" type="text/javascript">
    var a = document.getElementById('idResultsTableParent');
    var rows= a.getElementsByTagName('tr');
    rows[1].cells[1].innerText ="@{Presentation Variable}";
    </script>
    Editing the same post to remove irrelevant information.
    - Girish

  • Changing column names in a local query

    I have several underlying queries in my IR bqy(11.1.2.1). I need to be able to change column names in my final query(as the requirements keep changing constantly). Is there a way to do this without modifying the names in the original query(I don't want to create a bunch of computed items either).
    Thanks.

    I have several underlying queries in my IR bqy(11.1.2.1). I need to be able to change column names in my final query(as the requirements keep changing constantly). Is there a way to do this without modifying the names in the original query(I don't want to create a bunch of computed items either).
    Thanks.

  • How to set column names when not using object of row data in  constructer

    hello i am using JTable constructer as
    public JTable(int numRows,
    int numColumns)
    can i set column names for the columns .How?

    hi,
    sure you can: Create a subclass of DefaultTableModel and overwrite the method public String getColumnName(int) which returns the column name of a specific column. Then use this subclass as the data model for the table.
    best regards, Michael

  • Setting column names in JTable

    can n e one tell me how to set column names for JTable..
    i don't wanna use the JTable constructor ... cuz
    my column names change...

    this is how i did it once...hope it helps
    Vector columnNames = new Vector();
    JTable previewTable = new JTable();
    previewTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    previewScrollPane.getViewport().add(previewTable, null);
    int colNo = 2; // i am displaying 2 columns
    columnNames.add("Col One");
    columnNames.add("Col Two");
    String[] tableColumnNames = {"Id Name","Type"};
    DefaultTableModel aModel = (DefaultTableModel) previewTable.getModel();
    aModel.setColumnIdentifiers(tableColumnNames);
    //add data to the table
    .//loop
    aModel.addRow(objects);
    previewTable.revalidate();
    previewTable.setModel(aModel);

  • How to validate column name in dynamic made sql?

    Oracle db, jdbc, web app with struts2/spring.
    Example table could be this:
    CREATE TABLE album
    album_id number(10)  not null,
      artist  varchar2(50) not null,
    title  varchar2(50) not null,
      released  DATE,  
      CONSTRAINT album_pk PRIMARY KEY (album_id)
    );In may app the user MAY search, MAY sort, and the result from an select might return 10.000 rows.
    The basic sql usually look like this.
    String sql = "select album_id, artist, title, released from album";Then in the html page the user can add search criteria for each column. Like type "iron maiden" in artist field, put "1982" in released field. And you all know what the exceptionally result should be from that :)
    Now I need to modify the sql a bit:
    if( artist search field contains stuff )
       sql = sql + " where nvl( artist,' ') like ?"
    }we try use prepared statements right? So we use ? as placeholders, and then add "iron maiden" into this statement later on.
    Nice, no big fuzz right, and pretty safe from sql injections i guess.
    But now I have to have an if/else for every single field in the table. Boring. In my app I got like 25 tables like this, with 20 columns minimum. Copy/Paste have never been so boring.
    I also might have to add "order by" with user selected columns and their order. I have to count the query to get total result in case i got to split it up in pages. So there is alot of if/else and sql = sql + "more stuff", and sticking to ? and pure prepared statements is impossible.
    But doing this is not good either:
    for( each element in a map)
      sql = sql + " and nvl( " + key + ",' ') like ?"
    }Where key is "artist".
    In struts and other tag libs its easy to make kode like:
    <s:textfield name="model.addSearch( 'artist' )" value="%{model.getSearch( 'artist' )}" size="30" />
    Silly example maybe, but just to make a point.
    Inputed values in an html form, can very easily be a part of a dynamic created sql - which becomes a security problem later on.
    Artist is an column name. Key should be validated if it contained an valid column name.
    I could make a list of strings, containing valid column names to check against.
    My question is if there is possible to get this type of information from the database, so I don't have to hand-make these lists?
    But I also want to keep the number of heavy and slowing queries down.
    My app have like 25 tables now, and I could easily get away with hand-make everything, copy/paste around etc. But I have more projects and this question will be here next time too. And after there again...

    Etharo wrote:
    Metadata. Then I have to query the database, take the result and use it for validating of input. If my sql only query 1 table, then this is ok. In this case I could do with that. But if the sql query mutliple tables, with sub-selects, unions etc. Then I might have to query all tables first, and even then I might not have what I want.
    The best way is of course to run the query, then get the metadata from that query - cause then im 100% sure what columns will be returned, and then I can validate with that.... 1 query is often not that slow. But I might query once to find total number of rows the query return in order to decide if we need to page the result. then query to get the metadata for validating input, then query to get the result... Maybe this is ok -but my head don't like it as an general ok thing to do, but I can't really say why...If you have a gui screen then it needs to correspond to some specific query. It can't be all possible combinations.
    So once you know the query you can obtain the meta data using a query that returns no results. Like the following.
    select * from mytable wheren 1 = 0
    >
    Jschell:
    I agree to what you say. I don't understood everything you said tho.
    Im not sure if you talk about having 1 search field (like google), and you input stuff there that might be in any columns.
    I have several search fields in one-to-one relasionship with view column/sql query column.
    Then you already know what the field represents. So validate it in the gui and not via the database.
    The first is way more advanced since you have to cover any input, any column, any case etc. Pluss add ranking. Lots of work for someone who have done little searchengines.
    Latter is simpler, but might also be limiting.Huh?
    As an example if you have a call center then the operators are not going to be doing unrestricted searches to find customers. They are going to look using a very limited set of data like the customer name and telephone number.
    >
    My job is very much like an consulent. They got an app, I shall add a new feature. The app is old and ugly coded. My boss ask how long it takes to make this, I say 2months, he decide 1 month. My dev time for features is rarely above 1 month, and I don't make much new apps.
    So I don't have the time to make advanced codegenerator, or spend time to evaluate various frameworks. Bringing an framework into the existing code is actually difficult. But I do want to improve the code, and add good code into the existing app that can be extended without evil pain.
    That doesn't jive with your OP. You made the following statement "My app have like 25 tables now, and I could easily get away with hand-make everything,...".
    That suggests that you are doing much more than simply updating an existing application.
    If you only need to add one new field then you should do only that. You shouldn't be attempting to add a system spanning validation system.
    On the other hand if you are in fact adding a validation system, then code generation makes it likely that it would take less time or no more than the same. And it is less likely to introduce bugs.
    Learn how to make an code generator? Well I guess thats what I asked help for - point me in the right direction if you could pls. Putting strings together to become code in an logic way is usually manageable, at least for simple querys. Evaluating that the generated code is good/safe - got no good clues...
    Learn about frameworks? Got no time. Hope I will get the time, but I won't. The customer must want to spend the money so I can get the time, that won't happen cause an framework does not add features, its only cost saving in terms of dev time, and maintenance time. The customer have no such focus/interest. They got a bit money to spend now and then regularily. i.e. government.
    I just want to try code as good as possible so I save myself from errors, painfull rewrites, and dev-time that gets out of proportions because of stupid code. So the question is actually about me trying to improve myself, its just that i don't know how right now.There are two goals.
    1. Implement a specific feature in an existing application.
    2. Learn a new way to solve problems.
    Nothing says that the second will help with the first. They should be addressed separately and your post doesn't make it clear what the first is so it is hard to say how it should be down.
    As for the second I already made a suggestion which provides two new ways to solve problems.

  • Resolve column names in a sql Query

    Hi Folks,
         I’m upgrading an application and there are database columns that have major changes that could affect production reports. I would like to survey v$SQL for a few days to see if these columns are affected. Here’s the problem.
    Looking at a SQL query to determine which columns are used is not nearly as easy as it sounds. Are there any oracle functions or 3rd party tools that can be used to list the columns used by a sql query? (this gets extremely tricky when subqueries become involved)
    For instance.
    select
    name, b.dep_id, employee_id
    From emp a
    Inner join v_department b on a.dep_id=b.dep_id
    Columns used:+
    Emp.name+
    Departments.dep_id (under the view)+
    Emp.employee_id+
    Emp.dep_id (from the join)+

    If you're on > 10g, you can use dbms_xplan with "all" option.
    It shows "column projection information" which is exactly what you want.
    UKJA@ukja102> set serveroutput on
    UKJA@ukja102>
    UKJA@ukja102> drop table t1 purge;
    Table dropped.
    Elapsed: 00:00:00.03
    UKJA@ukja102> create table t1(c1 int, c2 int);
    Table created.
    Elapsed: 00:00:00.03
    UKJA@ukja102>
    UKJA@ukja102> explain plan for
      2  select
      3    t1.c1, t1.c2, v.cnt
      4  from t1,
      5    (select /*+ no_merge */ c1, count(*) as cnt
      6        from t1
      7        group by c1) v
      8  where
      9    t1.c1 = v.c1
    10  ;
    Explained.
    Elapsed: 00:00:00.01
    UKJA@ukja102>
    UKJA@ukja102> @plan_all
    UKJA@ukja102> select * from table(dbms_xplan.display(null,null,'all'))
      2  /
    PLAN_TABLE_OUTPUT                                                              
    Plan hash value: 536125944                                                     
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |  
    |   0 | SELECT STATEMENT     |      |     1 |    52 |     6  (34)| 00:00:01 |  
    |*  1 |  HASH JOIN           |      |     1 |    52 |     6  (34)| 00:00:01 |  
    |   2 |   TABLE ACCESS FULL  | T1   |     1 |    26 |     2   (0)| 00:00:01 |  
    |   3 |   VIEW               |      |     1 |    26 |     3  (34)| 00:00:01 |  
    |   4 |    HASH GROUP BY     |      |     1 |    13 |     3  (34)| 00:00:01 |  
    |   5 |     TABLE ACCESS FULL| T1   |     1 |    13 |     2   (0)| 00:00:01 |  
    Query Block Name / Object Alias (identified by operation id):                  
       1 - SEL$1                                                                   
       2 - SEL$1 / T1@SEL$1                                                        
       3 - SEL$2 / V@SEL$1                                                         
       4 - SEL$2                                                                   
       5 - SEL$2 / T1@SEL$2                                                        
    Predicate Information (identified by operation id):                            
       1 - access("T1"."C1"="V"."C1")                                              
    Column Projection Information (identified by operation id):                    
       1 - (#keys=1) "T1"."C1"[NUMBER,22], "T1"."C2"[NUMBER,22],                   
           "V"."CNT"[NUMBER,22]                                                    
       2 - "T1"."C1"[NUMBER,22], "T1"."C2"[NUMBER,22]                              
       3 - "V"."C1"[NUMBER,22], "V"."CNT"[NUMBER,22]                               
       4 - (#keys=1) "C1"[NUMBER,22], COUNT(*)[22]                                 
       5 - "C1"[NUMBER,22]                                                         
    Note                                                                           
       - dynamic sampling used for this statement                                  
    40 rows selected.
    Elapsed: 00:00:00.01
    UKJA@ukja102>
    UKJA@ukja102>
    UKJA@ukja102> @end
    UKJA@ukja102> set echo offDion Cho

  • Not displaying column names in dynamic pages?

    I'd like to use a dynamic page as a detail page. In doing this I need a bit more freedom of design than what I now know is possible. Most important - I only need to print out the values returned by the SQL, not the column names as well. And I need to define the colors and fonts of the html table tags surrounding the returned values. How?
    It seems a bit strange that I am allowed to change the look and feel of the surrounding page elements through defining my own templates, and then have Oracle define how the elements placed in the templates are to appear.

    Hi,
    It is not possible to change the format the output coming from the <oracle> tags.
    Thanks,
    Sharmila

  • How to set column names in OVS search help of ALV EDIT

    Hi All,
    I have a OVS search help for my ALV EDIT column.This OVS will have two columns,I need to give the names(name1 , name2)  to the columns.
    I am writing the below codo in phase 0.
          ls_text-name = 'Column1'.
          ls_text-value = 'name1'.
          INSERT ls_text INTO TABLE lt_column_texts.
          ls_text-name = 'Column2'.
          ls_text-value = 'name2'.
          INSERT ls_text INTO TABLE lt_column_texts.
          ovs_callback_object->set_configuration(
                    label_texts  = lt_label_texts
                    column_texts = lt_column_texts
                    group_header = lv_group_header
                    window_title =  lv_window_title
                    table_header = lv_table_header
                    col_count    = 2
                    row_count    = 20 ).
    Below code in Phase 3.
          Assign ovs_callback_object->selection->* to <ls_selection>.
          if <ls_selection> is assigned.
            ovs_callback_object->context_element->set_attribute(
            name = `ATR1`
            value = <ls_selection>-Column1 ).
          endif.
    But,the column names are not getting set.Please provide your inputs.
    Regards,
    Salma

    hi,
    About your requirement, i don't know why you need to code in "Phase 3" of OVS.
    "Phase 3" is used for transporting your selected value to Your ALV.
    I think, the reason why you loose the result table including your customized column title, is that you loose the "Phase 2".
    Generally, in the past i used OVS as the following code simply.Just one example:
    * declare data structures for the fields to be displayed and
    * for the table columns of the selection list, if necessary
      types:
        begin of lty_stru_input,
    *   add fields for the display of your search input here
          carrid type string,
          connid type string,
        end of lty_stru_input.
      types:
        begin of lty_stru_list,
    *   add fields for the selection list here
          carrid type string,
          connid type string,
          text   type string,
        end of lty_stru_list.
      data: ls_search_input  type lty_stru_input,
            lt_select_list   type standard table of lty_stru_list,
            ls_text          type wdr_name_value,
            lt_label_texts   type wdr_name_value_list,
            lt_column_texts  type wdr_name_value_list,
      case ovs_callback_object->phase_indicator.
        when if_wd_ovs=>co_phase_0.  "configuration phase, may be omitted
    *   in this phase you have the possibility to define the texts,
    *   if you do not want to use the defaults (DDIC-texts)
          ls_text-name = 'CARRID'.  "must match a field name of search
          ls_text-value = 'Search Field-Carrid'.
          insert ls_text into table lt_label_texts.
          ls_text-name = 'CONNID'.  "must match a field name of search
          ls_text-value = 'Search Field-Connid'.
          insert ls_text into table lt_label_texts.
          ls_text-name = 'CARRID'.  "must match a field in list structure
          ls_text-value = 'Result-Carrid'.
          insert ls_text into table lt_column_texts.
          ls_text-name = 'CONNID'.  "must match a field in list structure
          ls_text-value = 'Result-Connid'.
          insert ls_text into table lt_column_texts.
          ls_text-name = 'TEXT'.  "must match a field in list structure
          ls_text-value = 'Result-Text'.
          insert ls_text into table lt_column_texts.
          lv_group_header = 'Group Header'.
          lv_window_title = 'Window Title'.
          lv_table_header = 'Table Header'.
          ovs_callback_object->set_configuration(
                    label_texts  = lt_label_texts
                    column_texts = lt_column_texts
                    group_header = lv_group_header
                    window_title = lv_window_title
                    table_header = lv_table_header
                    col_count    = 3
                    row_count    = 8 ).
    when if_wd_ovs=>co_phase_2.
    *   If phase 1 is implemented, use the field input for the
    *   selection of the table.
    *   If phase 1 is omitted, use values from your own context.
          if ovs_callback_object->query_parameters is not bound.
    ******** TODO exception handling
          endif.
          assign ovs_callback_object->query_parameters->*
                                  to <ls_query_params>.
    SELECT * INTO CORRESPONDING FIELDS OF TABLE lt_select_list FROM ZTABLE_FLIGHT
                           WHERE CARRID LIKE lw_carrid
                                 AND CONNID LIKE lw_connid
    *ovs_callback_object->set_output_table( output = lt_select_list ).*
    Hope it can help.
    Best wishes.

  • C# : Get Column name for an Insert Query from The Selected GridView Row.

    Hi Guys, I am trying to insert data in an SQL table by executing an Insert Query. 
    The problem is that I need to get the column name from a cell in the selected gridview Row.
    Here's the snippet:
    SqlCommand cmd30 = new SqlCommand("insert into mytable ( '"+GridView7.SelectedRow.Cells[0].Text+"' , r_id) values ('"+ GridView7.SelectedRow.Cells[1].Text +"', '"+TextBox1.Text+"')",con30);
            cmd30.ExecuteNonQuery();
    **r_id is not a Primary Key.
    The Error is get is:
    Incorrect syntax near 'r_id'.
    Any Help will be appreciated.
    Thanks,
    Shaleen
    TheHexLord

    Hi TheShaleen,
    Like your title mentioned.GridView control is a web class.This forum is to discuss problems of C# development.  Your question is not related to the topic of this forum.
    You'll need to post it in the dedicated ASP.Net Forum  for more efficient responses, where you can contact ASP.NET experts. Thanks for understanding.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to replace part of column name with dynamic value

    I have the following construction in an update transaction:
    $upd_blg_user_usr->addColumn("report_1_user", "NUMERIC_TYPE", "VALUE", "{rsCatReport.id_report}");
    The dynamic value, {rsCatReport.id_report}, gets a url variable.
    I want this variable to replace the "1" in the column name "report_1_user". Something like this:
    $upd_blg_user_usr->addColumn("report_{rsCatReport.id_report}_user", "NUMERIC_TYPE", "VALUE", "{rsCatReport.id_report}");
    That construction, however, does not work. Prevents the page from loading. I've tried different constructions but have not hit one one that works.
    First, I'm not sure anything will work and second, if some different construction will work, I don't know what it is.
    Can anyone answer these questions. Thanks in advance for your help.

    What? Are you some kind of genius?
    Yes that works perfectly. Thanks as always!
    Here's the rationale. The same basic form appears on many different pages. The only difference among the forms is the outcome of submitting the form. The form on different pages takes you to a different download page and a database column is marked to signify that the user downloaded that form. For instance:
    report_1_usr
    report_2_usr
    report_3_usr
    And so forth...
    Up to now each form has had to include the url variable so the submit would take the user to the right download page and it has had to include a unique reference to the correct database column.
    Now I can echo or insert that url variable all over the place, including the reference to the column name in the transaction, so I can use a single instance of the form and include it on all pages.
    Thanks for helping me figure out the last step.

  • Modifying Internal Table row - The column name is dynamic

    Hi,
    I need to update the internal table as described below,
    Assume that i have 10 columns in my internal table and i need to modifying the column value in row, which is dynamic.
    for example, i'm writing it in Subroutine and it has 3 formal parameter
    1) Key field value
    2) Column name
    3) Value of the column
    in my subroutine i need to write code to modify the row, which should handle the columns dynamically.
    Samples,
    7th record i need to modify the 4th column value.
    4th record i need to modify the 9th column value.
    Please guide me to handle this requirement.write me if i'm not clear.
    ...Nandha

    For the column check the ASSIGN statement:
    No system here, but I think it is:
    ASSIGN COMPONENT <index> OF STRUCTURE <structure> TO <field-symbol>.
    For the row:
    READ TABLE <itab> INDEX <index> INTO <work area>.
    --> For your 1. example you could write:
    READ TABLE <itab> INDEX 7 INTO <work area>.
    ASSIGN COMPONENT 4 OF STRUCTURE <work area> TO <field-symbol>.
    <field symbol> now points to the 4th column of the 7th row.
    Guenther

  • How to pull only column names from a SELECT query without running it

    How to pull only column names from a SELECT statement without executing it? It seems there is getMetaData() in Java to pull the column names while sql is being prepared and before it gets executed. I need to get the columns whether we run the sql or not.

    Maybe something like this is what you are looking for or at least will give you some ideas.
            public static DataSet MaterializeDataSet(string _connectionString, string _sqlSelect, bool _returnProviderSpecificTypes, bool _includeSchema, bool _fillTable)
                DataSet ds = null;
                using (OracleConnection _oraconn = new OracleConnection(_connectionString))
                    try
                        _oraconn.Open();
                        using (OracleCommand cmd = new OracleCommand(_sqlSelect, _oraconn))
                            cmd.CommandType = CommandType.Text;
                            using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                                da.ReturnProviderSpecificTypes = _returnProviderSpecificTypes;
                                //da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                                if (_includeSchema == true)
                                    ds = new DataSet("SCHEMASUPPLIED");
                                    da.FillSchema(ds, SchemaType.Source);
                                    if (_fillTable == true)
                                        da.Fill(ds.Tables[0]);
                                else
                                    ds = new DataSet("SCHEMANOTSUPPLIED");
                                    if (_fillTable == true)
                                        da.Fill(ds);
                                ds.Tables[0].TableName = "Table";
                            }//using da
                        } //using cmd
                    catch (OracleException _oraEx)
                        throw (_oraEx); // Actually rethrow
                    catch (System.Exception _sysEx)
                        throw (_sysEx); // Actually rethrow
                    finally
                        if (_oraconn.State == ConnectionState.Broken || _oraconn.State == ConnectionState.Open)
                            _oraconn.Close();
                }//using oraconn
                if (ds != null)
                    if (ds.Tables != null && ds.Tables[0] != null)
                        return ds;
                    else
                        return null;
                else
                    return null;
            }r,
    dennis

  • Setting column names in a sql statement

    hello everyone i hope someone can help me.
    i want a sql statement that gets the column names from a arraylist for example
    String sql = ("INSERT INTO Cust (and i want this part to get what is in the arraylist) values (?, ?, ?)");
    is there any way i can do this?
    thanks for your time
    loftty

    hello again
    well when i try to compile it i get an error saying [ODBC SQL server driver] COUNT field incorrect or syntax error.
    what is the problem here?
    and regarding my previous question my arraylist holds three names (firstname, lastname and postcode) now i want to be able to add 10 values to the column name firstname, then i want to add 8 values to the column name lastname and then 9 values to column name postcode.
    i hope this is a better understanding if not let me know and i will try and explain again.
    thanks for your time
    loftty
    StringBuffer sb = new StringBuffer("INSERT INTO Cust (");
                                                 Iterator it = arr.iterator();
                                                 while (it.hasNext())
                                                      String col = (String) it.next();
                                                      sb.append(col);
                                                      if (it.hasNext())
                                                           sb.append(',');
                                                      sb.append(") values (?, ?, ?)");
                                                      String sql = sb.toString();
                                                 PreparedStatement prepStmt = con.prepareStatement(sql);
                                                           prepStmt.setString(1, "hello");
                                                           prepStmt.setString(2, "hi");
                                                           prepStmt.setString(3, "bye");
                                                           prepStmt.executeUpdate();
                                                           prepStmt.close();

  • Deciphering column names in a join query using jdbc

    hi all....
    I am making a database adapter for a generic report generater. This adapter would be forming queries involing various tables. There are two ways of doing it . I fire an sql on parent table to get the keys and then go to child table for each one of them or i form a join query to get desired result.
    i want to go with the later approach where my query would be forming a join. The problem comes when table involved in this join has columns with the same name. for eg if a column "NOTE" is there in table A as well as table B on which i have a join. Resultset returns me with two "NOTE" columns and i cannot recognize which one belongs to which table.
    all API calls including getString("Note") seems to be referring to the first occurence of "Note" column.
    Also getTableName() and getSchemaName() APIs on resultsetMetadata doesnt return in anything in case of joins.
    Any pointers would be most appreciated.
    cheers
    vivek

    thanks for suggesting this solution ... though i had thought of the same onece .... unfortunately i cannot implement something like this coz out of the result set i have to instantiate an object hierarchy depending on the schema ....
    this also puts me in a doubt whether i can use join in my case.
    for eg ... .
    lets say we have a customer talbe and and address table which has one to many relationship .... one contact can have multiple addresses.
    Assuming a contanct "Joe Bloggs" having 3 addresses ...a query like following
    select contact.firstname contactfirstname , address.streetname addressstreetname from contact , address where contact.contactid = address.contactid
    this would return me 3 rows and i can also recognize various columns with their aliases ..
    but i would lose an important fact that i have to create one java object for contact class and 3 instances for addresses which i have to return finally.
    this means that i would like to return an object hierarchy with one contact object and 3 address object underneath it linked with contactid.
    Any other suggestions after reading the complete requirement are most welcome ...sorry for not puting the entire thing at first.
    i guess the only soln left is to visit contact and address table separately. :(

Maybe you are looking for