DOCUMENTING SELECT STATEMENT

Hi All,
I been working with databases (ORACLE, MSSQLSERVER, SQLANYWARE) for last couple of years. SELECT statement comes into picture very frequently.
But yet I am unable to find any template, tool or hint to document the SELECT statement, so that other developers can understand its flow and relationships among source files. Every time a source given to developer (other than who actually write it) with SELECT statement, it takes long time to understand.
Any hint/help would be highly appreciated.
Regards.

For 90-some percent of the SQL statements you're likely to come across, this would seem to be an issue of developer training rather than of documentation. If your developers are accostomed to thinking in terms of set-based processing rather than procedural-based programming, the structure of a SQL statement ought to be rather self-explanatory. If there are a lot of DECODE statements or the SQL statement is doing something unusual, putting an explanatory comment nearby might be helpful.
Of course, this assumes that the developers are reasonably familiar with the data model of the underlying tables. If not, make sure they have the necessary ERD(s) and other documentation.
Justin
Distributed Database Consulting, Inc.
www.ddbcinc.com/askDDBC

Similar Messages

  • Secondary Index Select Statement Problem

    Hi friends.
    I have a issue with a select statement using secondary index,
    SELECT SINGLE * FROM VEKP WHERE VEGR4 EQ STAGE_DOCK
                                      AND VEGR5 NE SPACE
                                      AND WERKS EQ PLANT
            %_HINTS ORACLE
            'INDEX("&TABLE&" "VEKP~Z3" "VEKP^Z3" "VEKP_____Z3")'.
    given above statement is taking long time for processing.
    when i check for the same secondary index in vekp table i couldn't see any DB index name with vekp~z3 or vekp^z3 or vekp____z3.
    And the sy-subrc value after select statement is 4. (even though values avaliable in VEKP with given where condition values)
    My question is why my select statement is taking long time and sy-subrc is 4?
    what happens if a secnodary index given in select statement, which is not avaliable in that DB Table?

    Hi,
    > ONe more question: is it possible to give more than one index name in select statement.
    yes you can:
    read the documentation:
    http://download.oracle.com/docs/cd/A97630_01/server.920/a96533/hintsref.htm#5156
    index_hint:
    This hint can optionally specify one or more indexes:
    - If this hint specifies a single available index, then the optimizer performs
    a scan on this index.  The optimizer does not consider a full table scan or
    a scan on another index on the table.
    - If this hint specifies a list of available indexes, then the optimizer
    considers the cost of a scan on each index in the list and then performs
    the index scan with the lowest cost. The optimizer can also choose to
    scan multiple indexes from this list and merge the results, if such an
    access path has the lowest cost. The optimizer does not consider a full
    table scan or a scan on an index not listed in the hint.
    - If this hint specifies no indexes, then the optimizer considers the
    cost of a scan on each available index on the table and then performs
    the index scan with the lowest cost. The optimizer can also choose to
    scan multiple indexes and merge the results, if such an access path
    has the lowest cost. The optimizer does not consider a full table scan.
    Kind regards,
    Hermann

  • Using if the else logic in regards to a select statement for a report

    Hi all,
    I've a question regarding if then else logic in Oracle.
    I'm developing a report application which contains 3 selectlists
    - ProductGroup - SubGroup - Manufacturer
    Each one containing several values. And are based on eachother, meaning if you select an item from the PG list, you only get the SG items regarding the PG item you've choosen before. The process logic should be as the following:
    When a user selects one item from for example the PG list, the query will be:
    select * from x where PG = :P_PG
    and the report displays all the items in the PG category selected
    The other two bindvariables would be null as the user didn't pick them
    If he then proceeds and selects one item from the SG list, the query would be:
    select * from x where PG = :P_PG and SG = :P_SG
    and the report displays all the items in the PG and SG category selected
    If he then proceeds and selects one item from the MA list, the query would be:
    select * from x where PG = :P_PG and SG = :P_SG and MA =:P_MA
    and the report displays all the items in the PG and SG and MA category selected
    Now, I've read some documentation about the decode function, but I can't figure it out, please help.
    Peter

    Okay, Chet, have set it up on htmldb, so you can see my problem, will go in high detail, it is not producing what I want. Example on htmldb:
    DEMO/test
    http://htmldb.oracle.com/pls/otn/f?p=33229:6
    Defenitions:
    3 LOV's, namely:
    - LOVPG - select distinct productgroep, productgroep pg from plijst
    - LOVSG - select distinct subgroep, subgroep sg from plijst where productgroep = :P6_LOVPG
    - LOVLE- select distinct leverancier, leverancier le from plijst where productgroep = :P6_LOVPG and subgroep = :P6_LOVSG
    3 Selectitems with submit, namely:
    - :P6_LOVPG
    - :P6_LOVSG
    - :P6_LOVLE
    Report region select statement:
    select * from plijst where (productgroep = :P6_LOVPG or :P6_LOVPG IS NULL) and (subgroep = :P6_LOVSG or :P6_LOVSG IS NULL) and (leverancier = :P6_LOVLE or :P6_LOVLE IS NULL)
    Branch to:
    Branche to page on submit after processing
    What it should do is:
    When you select an item from the first selectlist, productgroep, the report should show all rows containing the specified productgroep.
    When the user selects the next item in the subgroep selectlist, the report should show all rows containing the previously selected prodctgroup and the just selected subgroep.
    When the user selects the final item , the report should show all rows based on all three selected itemvalues, productgroep, subgroep, leverancier.
    The problem is that with this setup the report is only generated after the final selectlist choice of the user. But the user should see a report before that, going deeper into the structure. Hope, you see my problem?
    Sincerely,
    Pete

  • Limitation on SQL executing select statement from ADO and Oracle 8.1.7.1 OleDB Driver

    Hi,
    we are running a query with a big dunamic select statement from VB code using ADO command object. When Execute method is called system hangs and control won't return back to the application. it seems to be that there is some type limitation on Query string length. Please tell us if there is any?
    we are running Oracle 8.1.7 Server on Windows 200 Server and connecting from a W2K professional, ADO 2.6 and Oracle OLEDB 8.1.7.1 OLEDB Driver.
    Sample code:
    Dim rs As ADODB.Recordset
    Dim cmd As ADODB.Command
    Set cmd = New Command
    With cmd
    .CommandText = ' some text with more than 2500 characters
    .CommandType = adCmdText
    Set rs = .Execute
    End With
    when i debug using VB6 and when .Execute line is called system hangs or return a message method <<somemethod> of <<some class name>> failed error.
    Any help is appreciated.
    Thanks,
    Anil

    A stored procedure would only slow you down here if it was poorly written. I suspect you want to use the translate function. I'm cutting & pasting examples from the documentation-- a search at tahiti.oracle.com will give you all the info you'll need.
    Examples
    The following statement translates a license number. All letters 'ABC...Z' are translated to 'X' and all digits '012 . . . 9' are translated to '9':
    SELECT TRANSLATE('2KRW229',
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    '9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX') "License"
    FROM DUAL;
    License
    9XXX999
    The following statement returns a license number with the characters removed and the digits remaining:
    SELECT TRANSLATE('2KRW229',
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789')
    "Translate example"
    FROM DUAL;
    Translate example
    2229
    Also, LIKE '%<string>%' is going to be rather expensive simply because it has to compare the entire string and because it forces full table scans, rather than using indexes. You could speed this sort of query up by using interMedia Text (Oracle Text now in 9i). If you can eliminate one of the '%' options, you could also improve things.
    My guess is that your stored procedure is inefficient and that's causing the problem-- 5k rows per table should be pretty trivial.
    If you post your query over on the PL/SQL forum, there are better performance tuners than I that might have more hints for you. To get really good advice, though, you'lllikely have to get at least the execution plan for this statement and may need to do some profiling to identify the problem areas.
    Justin

  • Edit an object's select statement of OLAP universe SAP BW

    Hi everybody
    I am new at working with Olap Universes BW, and I have to edit one universe SAP BW, I don't know if I can to use substring function on a select statement, for example  substring([0D_DIV].[LEVEL01],5,5), I try to use this function but I have a error,
    Could you help me? I need to returns part of a string, is correct to do it on a universe or is better to do at BW.

    Hi,
    First of all I recommend you read the documentation that gives you information about OLAP universes and especially SAP BW universes.
    I also recommend to download documents related to SAP universes deployment, administration and customization:
    [OLAP Universes - how to samples and recommendations |https://wiki.wdf.sap.corp/wiki/display/globalregions/OLAPUniverses-howtosamplesand+recommendations]
    [SAP Integration |https://wiki.wdf.sap.corp/wiki/display/globalregions/SAP+Integration]
    Now you can customize expression using MDX in OLAP universes. MDX expressions must be enclosed with <EXPRESSION></EXPRESSION> XML tags.
    Unfortunately SAP BW MDX does not support calculations that return string or date values.
    The onlyway to return string is to use NAME or UNOIQUENAME attribute.
    See answers I already in the forum: [Forum answer |Re: Create new dimension on top of SAP BW data]
    Regards
    Didier

  • How to use a select statement with chinese characters?

    I am currently developing a java servlet<using tomcat 4.x> which allows me to use select statement to retrieve results from the Microsoft SQL Server 2000 database. I am using a simple form to get the parameter for querying. The main problem i'm facing is that there are chinese information in the SQL database, but i can't retrieve it through the sql statement with the chinese characters input<thru the form with the help of NJ STAR>in the WHERE condition. When i execute the statement, it returns me no results even though the rows are present in the database.
    Does anyone have the solution to using chinese words in the WHERE clause of the select statement to retrieve results with columns which contains chinese characters? Please help me. Thanks everyone. :)
    PS: when i cut and paste those characters in the sql database and paste onto java.. it is ??? in questionmarks.. but when i paste them into excel 2000.. its shown as chinese chars again..
    please heelppp~~

    Greetings,
    PS: when i cut and paste those characters in thesql
    database and paste onto java.. it is ??? in
    questionmarks.. but when i paste them into excelThis is why the SELECT is not returning any results.
    You need to set the character encoding set on your
    statement and parameters for the characters to be
    properly translated. Refer to the charsetName
    parameter in the String class constructor in your API
    docs and also to
    $JDK_DOCS/guide/intl/encoding.doc.html in your JDK
    documentation.
    2000.. its shown as chinese chars again..Because Office programs are performing the same kind
    of character translation with the appropriate MS APIs.
    please heelppp~~Regards,
    Tony "Vee Schade" Cookis it possible for you to show me some coding examples? i don't really understand what is to be done in order to set the char set and what does it really do.. tried reading up but still dun understand.. :(
    pardon my shallow knowledge of java..
    ok..
    The thing is when i used an insert statement with chinese characters of GBK format hardcoded into the java servlet and then i use the insert statement to insert the chars into the database, it cannot be seen as a chinese word when i off the NJStar. and then it can be searched out with my current form of servlet.. below is my coding of the servlet..
    note: i've set my html file to charset = GBK
    //prototype of Search engine...
    //workable for GBK input and output...
    import java.io.*;
    import java.io.OutputStream;
    import java.io.IOException;
    import javax.servlet.http.*;
    import javax.servlet.ServletException;
    import java.util.*;
    import java.sql.*;
    import java.nio.charset.Charset;
    public class SearchBeta extends HttpServlet {
         private Vector musicDetails = new Vector();
         private String query = "";
         public void service (HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException, UnsupportedEncodingException {
              query = req.getParameter ("T1");
              System.out.println("before:"+query);
              String type = req.getParameter ("D1");//type
              query = req.getParameter ("T1");
              //query = "������";
              System.out.println("after:"+query);
              getResults(type,query);
              System.out.println("locale = :"+req.getLocale());
              res.setContentType ("text/html;charset=GBK");
              PrintWriter out = res.getWriter();
              out.println("<html>");
              out.println("<head>");
              out.println("<body bgcolor = \"black\">");
              out.println("<font face = \"comic sans ms\" color=\"Cornsilk\">");
              if (query.length()==0)
                   out.println ("Please key in your search query.");
              else if (musicDetails.size()==0)
                   out.println ("Sorry, no results matching your search can be found.");
              else {
                   out.println("<center>");
                   out.println("<table cellspacing = \"50\">");
                   int i = 0;
                   //Display the details of the music
                   while (i<musicDetails.size()) {
                        Results details = (Results)musicDetails.get(i);
                        String dbArtist = "";
                        String dbAlbum = "";
                        String dbTitle = "";
                        String dbCompany = "";
                        dbAlbum = details.getAlbum();
                        dbTitle = details.getTitle();
                        dbCompany = details.getCompany();
                        dbArtist = details.getArtist();
                        try{
                             dbAlbum = new String(dbAlbum.getBytes("ISO-8859-1"),"GBK");
                             dbTitle = new String(dbTitle.getBytes("ISO-8859-1"),"GBK");
                             dbCompany = new String(dbCompany.getBytes("ISO-8859-1"),"GBK");
                             dbArtist = new String(dbArtist.getBytes("ISO-8859-1"),"GBK");//correct translation.
                        catch(UnsupportedEncodingException e){
                             System.out.print(e);
                             e.printStackTrace();
                        String dbImage_loc = details.getImage();
                        out.println("<tr>");
                             out.println("<td><table>");
                                  out.println("<img src=C:\\Program Files\\Apache Group\\Tomcat 4.1\\webapps\\examples\\ThumbNails\\"+dbImage_loc+">");
                             out.println("<tr>");
                                  out.println("<th><font color=\"violet\"> Artist: </font></th>");
                                  out.println("<td><font color=\"Cornsilk\">"+dbArtist+"</font></td>");
                             out.println("</tr>");
                             out.println("<tr>");
                                  out.println("<th><font color=\"violet\"> Title: </font></th>");
                                  out.println("<td><font color=\"Cornsilk\">"+dbTitle+"</font></td>");
                             out.println("</tr>");
                             out.println("<tr>");
                                  out.println("<th><font color=\"violet\"> Company: </font></th>");
                                  out.println("<td><font color=\"Cornsilk\">"+dbCompany+"</font></td>");
                             out.println("</tr>");
                             System.out.println("album: "+ dbAlbum);
                             out.println("<tr>");
                                  out.println("<th><font color=\"violet\"> Album: </font></th>");
                                  out.println("<td><font color=\"Cornsilk\">"+dbAlbum+"</font></td>");
                             out.println("</tr>");
                             System.out.println("company: "+ dbCompany);
                             out.println("</table></td>");
                        out.println("</tr>");
                        i++;
                   out.println("</table>");
                   out.println("</center>");
              out.println("</font>");
              out.println("</body>");
              out.println("</head>");
              out.println("</html>");
              out.close();
              //to remove all the elements from the Vector
              musicDetails.removeAllElements();
         //get Searched Music Details and store in Results object which is stored in musicDetails vector
         public void getResults (String type, String searchQuery) {
              try {
                   Class.forName ("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                   Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=music","sa","kokkeng");
                   Statement stmt = con.createStatement();
                   String query = "SELECT * FROM MusicDetails WHERE "+type+" = '"+searchQuery+"'";
                   ResultSet rs = stmt.executeQuery(query);
                   while (rs.next()) {
                        String artist = rs.getString("Artist");
                        String title = rs.getString("Song");
                        String company = rs.getString("Company");
                        String album = rs.getString("Album");
                        String image_loc = rs.getString("Image");
                        Results details = new Results (artist,title,company,album,image_loc);
                        musicDetails.add(details);
                   stmt.close();
                   con.close();
              catch (Exception e) {
                   System.out.println(e.getMessage());
                   e.printStackTrace();
    with the above servlet i created, i can search out the data in the database which i've inserted through the insert statement. I still can't search for things i've keyed into the database directly using NJStar..
    thank you so much for helping.. really hope any one else who knows the answer to this will reply too... thank you all so much...
    -KK

  • Performance Tuning -To find the execution time for Select Statement

    Hi,
    There is a program that takes 10 hrs to execute. I need tune its performance. The program is basically reading few tables like KNA1,ANLA,ANLU,ADRC etc and updates to Custom table. I did my analysis and found few performance techniques for ABAP coding.
    Now my problem is, to get this object approved I need to submit the execution statistics to client.I checked both ST05 and SE30. I heard of a Tcode where we can execute a select statement and note its time, then modify and find its improved Performance. Can anybody suggest me on this.
    Thanks,
    Rajani.

    Hi,
    This is documentation regarding performance analysis. Hope this will be useful
    It is a general practice to use           Select  *  from <database>…     This statement populates all the values of the structure in the database.
    The effect is many fold:-
    •     It increases the time to retrieve data from database
    •     There is large amount of unused data in memory
    •     It increases the processing time from work area or internal tables
    It is always a good practice to retrieve only the required fields. Always use the syntax      Select f1  f2  …  fn  from <database>…      
    e.g.     Do not use the following statement:-
         Data: i_mara like mara occurs 0 with header line.
         Data: i_marc like marc occurs 0 with header line.
         Select * from mara
              Into table i_mara
              Where matnr in s_matnr.
         Select * from marc
              Into table i_marc
              For all entries in i_mara
              Where matnr eq i_mara-matnr.
         Instead use the following statement:-
                                       Data: begin of i_mara occurs 0,
                                            Matnr like mara-matnr,
                                                  End of i_mara.
         Data: begin of i_marc occurs 0,
              Matnr like marc-matnr,
                                            Werks like marc-werks,
                                                 End of i_marc.
         Select matnr from mara
              Into table i_mara
              Where matnr in s_matnr.

  • How can I select columns from a table EMP, using Select statement?.

    Hi Friends,
    How can I select columns from a table EMP?.
    I want to select columns of EMP table, using select statement.
    Please reply me urgently.
    Shahzad

    Something like this:
    scott@DBA> select empno,ename,job from emp;
         EMPNO ENAME      JOB
          7369 SMITH      CLERK
          7499 ALLEN      SALESMAN
          7521 WARD       SALESMAN
          7566 JONES      MANAGER
          7654 MARTIN     SALESMAN
          7698 BLAKE      MANAGER
          7782 CLARK      MANAGER
          7788 SCOTT      ANALYST
          7839 KING       PRESIDENT
          7844 TURNER     SALESMAN
          7876 ADAMS      CLERK
          7900 JAMES      CLERK
          7902 FORD       ANALYST
          7934 MILLER     CLERK
    14 rows selected.Check the documentation:
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9697
    Message was edited by:
    Delfino Nunez

  • Querying many tables at once from a select statement for specific values

    Hi all,
    I'm very new to PL/SQL and have a daunting task ahead of me. I'm pretty sure our database normalization scheme is all out of whack, which I dont have the experience to fix yet, but this is the task ahead of me without getting to change or fix our structure:
    in the universe has 1000+ tables.
    need--> Some of those tables have fields that contain a value that has to be changed.
    The only thing I have to go on is the column name will contain 'EMP'... but there is no specific naming convention for the column names.
    When I search on:
    select * from all_tab_columns where column_name like UPPER('%EMP%')
    It returns 750 rows. (So 750 rows = 750 columns in 500 different tables (some tables have 2 or more columns in it))
    tables names are random (table1, table2, etc).
    columns names are random with EMP in it (column1,column2,etc).
    I have 75 possible field values that I need to check each of those 750 columns for.
    Maybe this is too messy, but I'm looking at subqueries, joins, arrays, cursors, etc, anything to minimize the amount of work I have to do.
    I think this is too much to do a join with, but that seems to be what all the documentation is pointing me to.
    can you point me to a simple example of what i could
    write?
    the logic i see it would be
    run the select statement to grab the column names that meet EMP.
    one at a time, search each column in the corresponding table for the 75 values.
    return the results of rows for each column/table that meet one of the 75 unique values.
    I'll have to also update each of the 75 values to (used to be values 1, 2, 3 ... to new values X1, X2, X3, etc.)
    Any help at all would be very helpful,
    aspiring pl/sql programmer but having a rough time of it

    I think you're looking to do something like the following pseudocode:
    BEGIN
        FOR tblrec IN (SELECT table_name, column_name
                         FROM all_tab_columns
                        WHERE column_name LIKE '%EMP%')
        LOOP
            FOR rec IN (SELECT ROWID
                          FROM tblrec.table_name
                         WHERE REGEXP_LIKE(tblrec.column_name, '(expr1|expr2|...)')
            LOOP
                DBMS_OUTPUT.PUT_LINE(
                    'Found expression on ROWID ' || rec.rowid
                    || ' in column ' || tblrec.column_name
                    || ' on table ' || tblrec.table_name);
            END LOOP;
        END LOOP;
    END;

  • Exporting SQL Select statement to spreadsheet

    Hi all, basic question that I couldn't find the answer to while googling and searching the Oracle documentation.
    What is the code for exporting the result of a SQL Select statement to a spreadsheet such as Excel or Calc? In Oracle SQL Developer I tried saving the output as an XML file but it did not come out properly and I tried using EXPORT at the end of the statement but it gave an error message and I am not sure if this is the right command or what the syntax is. Thanks.

    Here's an example of one way to create CSV files that most spreadsheet type applications are able to read...
    As sys user:
    CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
    GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
    /As myuser:
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                         ,p_dir IN VARCHAR2
                                         ,p_header_file IN VARCHAR2
                                         ,p_data_file IN VARCHAR2 := NULL) IS
      v_finaltxt  VARCHAR2(4000);
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_fh        UTL_FILE.FILE_TYPE;
      v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
    BEGIN
      c := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      d := DBMS_SQL.EXECUTE(c);
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
        END CASE;
      END LOOP;
      -- This part outputs the HEADER
      v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
      FOR j in 1..col_cnt
      LOOP
        v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
      END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
      UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      IF NOT v_samefile THEN
        UTL_FILE.FCLOSE(v_fh);
      END IF;
      -- This part outputs the DATA
      IF NOT v_samefile THEN
        v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
      END IF;
      LOOP
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        EXIT WHEN v_ret = 0;
        v_finaltxt := NULL;
        FOR j in 1..col_cnt
        LOOP
          CASE rec_tab(j).col_type
            WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
            WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                        v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                        v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
          ELSE
            v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
          END CASE;
        END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
        UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      END LOOP;
      UTL_FILE.FCLOSE(v_fh);
      DBMS_SQL.CLOSE_CURSOR(c);
    END;This allows for the header row and the data to be written to seperate files if required.
    e.g.
    SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
    PL/SQL procedure successfully completed.Output.txt file contains:
    empno,ename,job,mgr,hiredate,sal,comm,deptno
    7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
    7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
    7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
    7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
    7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
    7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
    7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
    7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
    7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
    7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
    7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
    7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
    7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
    7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
    Adapt to output different datatypes and styles are required.
    There are other methods for specifically creating Excel workbooks with multiple sheets etc. and details can be found in the SQL and PL/SQL FAQ at the top of the forum:
    {message:id=9360007}

  • How to pass an array to a function from a SELECT statement

    Hi all. I have a problem with passing an array to a function directly from a SELECT statement.
    Here is what I want. If I have a function
    function AAA(arrayVar <ArrayType>) return number;
    I want to be able to call this function this way
    select AAA((2,3,4))
    from dual
    or this way
    select AAA((10,12))
    from dual
    In other words I want to be able to pass an arbitrary number of numbers to the function. And I want this to work in a SELECT statement.
    Does anyone have any ideas how to implement this? What <ArrayType> should I use?(I've read about VARRAY, nested tables in the Oracle documentation but as far as I've understood these array types are meant to be used within PL/SQL blocks).
    I found only this http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:208012348074 through Google but it didn't help me.
    Thank you in advance.

    > What <ArrayType> should I use?
    SQL data types - as 3360 showed above. You cannot use PL/SQL structures and user types in the SQL Engine.
    You can however use all SQL structures and types in PL/SQL.
    Arrays in SQL is created as collection type - basic o-o. The collection type (or class) serve as a container for instantiated objects or scalar type.
    This is covered in detail in [url http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14260/toc.htm]
    Oracle® Database Application Developer's Guide - Object-Relational Features

  • Need help in how to combine select statement

    Hi,
    Table1 (VIEWREST2005)
    - ip
    - msg
    - fulldata
    - ID
    Table2 (L200505)
    - ip
    - msg
    - fulldata
    I want to create one sql that can select from table 2 to table number 1. This is my select statement, but it cannot running. The different between this 2 table is only column ID.
    insert into VIEWREST2005(ip,msg,fulldata) values(select ip, msg,fulldata from L200505)
    Can anyone modified my sql statement.

    Why do you not refer to the Oracle® Database SQL Reference manual? Or do you think your SQL Kung Fu is good enough that no RTFM'ing is needed?
    On-line copies of all Oracle documentation is available via http://tahiti.oracle.com/
    BTW, the correct syntax for this flavoured INSERT is:
    INSERT INTO table SELECT .. FROM table
    Drop the VALUES clause as no literal values are supplied.

  • ABAP Joins or Separate select statements?

    Hi,
       I am working on a simulation of an implementation project as part of my in-house training programme. I am a rookie to ABAP and am now doing a print program that requires master data selection from tables ANLZ, LFA1, MSEG and CSKT, and also related line items from ANLA.
      As a former Java/.NET programmer I used to play with database joins. Now since ABAP joins are much simpler to use, I take the best advantage of them. For instance, in this particular program, I fetched related data from ANLZ, ANLA, LFA1 and CSKT into one internal table using a single select statement with ABAP joins.
      Now I happen to hear (in bits and pieces) that one should limit the use of nested joins to a certain extend. Instead, for the above program, I was advised to use 4 internal tables and to select data separately using FOR ALL ENTRIES. But in this case, we need to use 4 select statements, which means 4 database operations in place of just one.
      From ABAP documentation, I read that we can link upto 24 tables in a single select statement using ABAP joins.
    Can anyone clarify more about this? Which is high on performance?
    Using a single select statement using joins
    or
    Using multiple selects -- FOR ALL ENTRIES?
    Thanks and regards,
    Arun

    Hi Arun,
    you keep reading in these forums that FOR ALL ENTRIES is more performant, but this is simply not true.
    In your example, joining four tables for one DB operation is better than storing a lot of redundant data in internal tables just to perform four separate DB operations using FOR ALL ENTRIES.
    Make sure you join the tables correctly, i.e. link dependent tables giving their full primary key.
    FOR ALL ENTRIES can be used where effective join statements are not possible, e.g. when cluster tables are involved (like BSEG).
    Cheers
    Thomas
    Edit: check this out too: Inner Join or For All Entries

  • Execute an string as select statement

    Hi,
    I have a problem:
    I'm working with an older oracle verion (7.x??). I want to create a dynamic select statement. I create a string, e.g. v_sql_string, and want the database to execute it. What possibilities do I have to do this?
    Thanks in advance
    Mathias

    Yes,
    I went through the documentation, but it's only working with cursors.
    For better comprehension:
    This is the string:
    'select count(*) from invoice where sup_no ' || op_sup_no || ' v_sup_no and trpt_code ' || op_trpt_code || ' v_trpt_code and ship_no ' || op_ship_no || ' v_ship_no'
    I want to set the operators (op_xxx) dynamiclly. Isn't there something like RUN or EXECUTE, where I only have to pass a string, and the statement is executed ...
    But I don't know how ...
    Mathias

  • Email and Select statements

    This is probably a simple question. I'm trying to send an email and have the body generated from a select statement (eg. basically sending a report). I'm having trouble generating this report (eg. XXX := SELECT .....). I also want to know if it is possible to format the result into HTML (eg. format, links).
    Any help is appreciated.

    Hi Jugla,
    You can generate HTML from a PL/SQL SELECT statement using the PL/SQL web toolkit. Have a look at the documentation for this on the Oracle Technology Network at http://otn.oracle.com. There is a very good function list etc in the PL/SQL developers guide.
    With regards to your report, could you post the query you are currently using, and also give a slightly more detailed overview of what you are trying to achieve from thr query and how you are using it. I could hopefully then let you know what the problem is.
    Hope this helps a little bit,
    Cj

Maybe you are looking for

  • Problem establishing SSL VPN from only 1 IP address

    Hi, I'm experiencing strange problem. I can't establish SSL VPN connection from 1 IP address, but I don't have problem establishing SSL VPN from any other IP address. Remote IP address: 10.0.0.1 ASA's public IP address: 192.168.1.1 Output of packet-t

  • Cracking and popping over FireWire

    Audio or videos files played back with QuickTime over my FireWire connection are accompanied by quite a bit of cracking and popping. The crackling is not heard during quiet portions of the file. The format of the file doesn't seem to matter (.mov, .w

  • How to use logic:present tag in struts el tag

    Hi I am trying to use struts el tags in the jsp page.I am struggling with the following exception: Cannot find bean: "result" in any scope.I couldn't understand why this error is coming even i had the property "result" in my ActionForm. ActionForm: p

  • My HP Mini 110-1050NR will not start. Power LED, WiFi LED and Hard drive LED Flash

    My Mini 110-1050NR just died... When I try to turn it on the Power Switch LED, the WiFi Switch LED and the Hard Drive LED just flash on and off. There's no specific count. They continue to flash until I disconnect the battery.

  • Query: System date and time.

    hi all, Does any one know how to get the System Date and System Time using query. This is for my Formatted search. Thanks In advance. Bruce.