Select into aggregate function

Hi,
I have the following PL/SQL block that I am testing. The block reads a list of values from a local file and inserts the values into a select statement that uses an aggregate function. Here is my code:
DECLARE
f utl_file.file_type;
n COLa%TYPE; --holds values from the file
v COLb%TYPE; --holds value returned by select statement
BEGIN
f := utl_file.fopen(dir,file.txt,'R');
loop -- loop through file
     utl_file.get_line(f,n);
     if length(n) <> 0 then
          SELECT max(A0.COLa) into v
          FROM (SELECT AOB.COLa, A0.COLb
          FROM TAB1 A0,TAB2 A0B
          WHERE (A0.PK=A0B.PK) and A0B.COLa = n) A0;          
          IF SQL%rowcount = 0 THEN
               dbms_output.put_line('no rows);
          else
               dbms_output.put_line(v);
          end if;                    
     end if;     
end loop;
     utl_file.fclose(f);     
end;
Here is the error I get:
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SYS.UTL_FILE", line 98
ORA-06512: at "SYS.UTL_FILE", line 656
ORA-06512: at line 12
I checked the database for the first couple of values in the list and got rows. I also ran a simple PL/sql code to print values in the file successfully. So I dont know why it is returning no data found. From what I understand select into statement using aggregate functions will never raise this exception, so why I am getting this error?
Thanks.

Hi,
Actually, the SELECT ... INTO isn't the problem here.
Look at the error message:
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "SYS.UTL_FILE", line 98
ORA-06512: at "SYS.UTL_FILE", line 656
ORA-06512: at line 12The error is ocurring inside utl_file, which is being called at line 12 of your code. (That must be
utl_file.get_line(f,n);)
Utl_file.get_line raises NO_DATA_FOUND when it reaches the end of the file. (If it didn't you'd have an infinite loop, since your code doesn't have any exit strategy.)
You can put the call to get_line in its won BEGIN-EXCEPTION-END block, and trap the NO_DATA_FOUND error.
For example:
end_of_file := 0;
WHILE  end_of_file = 0;
loop -- loop through file
    BEGIN
        utl_file.get_line(f,n);
        if length(n) != 0 then          -- Use !=, because you can't post &lt;&gt; on this site
            SELECT  max(A0B.COLa)     -- No sub-query needed
            into    v
            FROM    TAB1 A0
            ,         TAB2 A0B
            WHERE   (A0.PK   = A0B.PK)
            and         A0B.COLa = n;
            IF SQL%rowcount = 0 THEN     -- Not needed: SELECT MAX ... without GROUP BY always returns 1 row
                dbms_output.put_line('no rows);
            else
                dbms_output.put_line(v);
            end if;
        end if;
    EXCEPTION
        WHEN  NO_DATA_FOUND
        THEN
            end_of_file = 1;
    END;
end loop;Edited by: Frank Kulash on Jul 17, 2009 2:51 PM

Similar Messages

  • Suggest me less expensive SELECT for aggregate function.

    Hi,
    I hv a SELECT statement with AGGREGATE function, but, as aggregates are expensive, so, want to replace it with less expensive SELECT statement, so, pls. let me know it, Wht can i use instaed, code is as below,
    CLEAR my_amount.
      SELECT SUM( wrbtr ) into my_amount from BSID
                              WHERE bukrs = p_bukrs
                              and   kunnr = p_konto
                              and   budat <= sy-datum.
    so, pls. let me know alternative(replace) SELECT which is less expensive performence wise
    thank you

    >
    M_S_Raju_0613 wrote:
    > Hi,
    >
    > I hv a SELECT statement with AGGREGATE function, but, as aggregates are expensive, so, want to replace it with less expensive SELECT statement, so, pls. let me know it, Wht can i use instaed, code is as below,
    >
    >
    CLEAR my_amount.
    >   SELECT SUM( wrbtr ) into my_amount from BSID
    >                           WHERE bukrs = p_bukrs
    >                           and   kunnr = p_konto
    >                           and   budat <= sy-datum.
    >
    > so, pls. let me know alternative(replace) SELECT which is less expensive performence wise
    >
    > thank you
    I don't think using SUM is a bad thing to do if you're using an index.  The only replacement would be to select all the data into an itab and add it up yourself and I don't think that doing this would be any quicker - it might even be slower because you would be bringing back more records rather than restricting the number of records brought back at database level which is what the SUM would do.  The thing I'd be concerned about here is that you're not taking acount of the SHKZG debit / credit flag.  But if all the lines you're dealing are credits or all are debits that won't matter to you.

  • Group By Select Statement aggregate function error.

    I am using Dreamweaver MX4 and have an ASP web page. I can easily do this in Access 2007 a simple "group by" sum totals statement.
    Why can I not get this to work on a web page? Are the "#" signs messing this up in the Code2 Select Statement?
    How can I get Code2 to work correctly? Code1 works fine. A user enters the customer and a date range on a form and submits request. I get error message in Dreamweaver. You tried to execute a query where the specified expression field3 is not part of an aggregate function
    Code1. This works fine SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #1/2/09# AND Field6 <= #1/30/09#  GROUP BY Field3, Field10
    Code2. I get error message SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #Date1# AND Field6 <= #Date2#  GROUP BY Field3, Field10

    I am using Dreamweaver MX4 and have an ASP web page. I can easily do this in Access 2007 a simple "group by" sum totals statement.
    Why can I not get this to work on a web page? Are the "#" signs messing this up in the Code2 Select Statement?
    How can I get Code2 to work correctly? Code1 works fine. A user enters the customer and a date range on a form and submits request. I get error message in Dreamweaver. You tried to execute a query where the specified expression field3 is not part of an aggregate function
    Code1. This works fine SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #1/2/09# AND Field6 <= #1/30/09#  GROUP BY Field3, Field10
    Code2. I get error message SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #Date1# AND Field6 <= #Date2#  GROUP BY Field3, Field10

  • Select with aggregate function MAX

    Hi,
    Can I write a query like:
    select field1 field2 MAX( field3 )
    from z_table
    into table itab
    for all entries in itab2
    where field1 = itab2-field1
         and field2 = itab2-field2.
    In the above case all the 3 fields are key fields.
    Thanks in advance.

    Hi,
    I did try it.. but got an error like: "The field "z_table~field2" from the select list is missing in the GROUP BY clause" but my aggregate funtion is used only for the field3..... So, I wanted to know if anybody has come across such a query....
    Thanks,

  • Select with aggregate functions? i.e. select max(code)...

    The code field on my user table is too small for the key field I want to use but it is still necessary I assume I must generate my own unique value.
    The DBDataSource.Query() method doesn't seem appropriate so should I create a SAPbobsCOM.Recordset and use the DoQuery method to select the maximum value currently in the user table?
    I found some mentions of requiring such a select statement on this board but no examples of the actual code. I'll go ahead and try the DoQuery method unless I hear of something more appropriate.
    Also, I saw a comment that a future release of SAP would have a larger code field for user tables but obviously that didn't happen in 6.7.
    Thanks for any comments.
    Bill Faulk

    Here's what I came up with...
    If you are happy with 99,999,999 records instead of 4,294,967,295 then I guess you can forego the hexadecimal bit. I'd welcome any alternatives if someone has one.
    With the hex:
    private string GetNextKey(string strTable)
        SAPbobsCOM.Recordset rs =
            (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
        rs.DoQuery("select isnull(max(code),'00000000') from [" + strTable + "]");
        string strCode = (string)rs.Fields.Item(0).Value;
        int intKey = Convert.ToInt32(strCode,16) + 1;
        return intKey.ToString("X8");
    No Hex:
    private string GetNextKey(string strTable)
        SAPbobsCOM.Recordset rs =
          (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
        rs.DoQuery("select isnull(max(code),'00000000') from [" + strTable + "]");
        string strCode = (string)rs.Fields.Item(0).Value;
        int intKey = Convert.ToInt32(strCode) + 1;
        return intKey.ToString("00000000");

  • Aggregate Functions in SELECT

    Hi Friends,
      Is it possible to have an aggregate function while using Inner join and GROUP BY? Its not working for me.
    Prompt replies would be rewarded.
    Thanks in advance.
    Regards
    Tamilarasan.
    Message was edited by: Tamilarasan Lakshmanan

    I'm not sure what you mean by 'not working', but you can try something like:
    * select data: parked documents in value type 54 (invoice) --------
      select  fmifiit~knbelnr bkpf~bstat
          count( distinct fmifiit~fmbelnr )
       into (wa_error-belnr, wa_error-bstat, wa_error-count)
       from fmifiit inner join bkpf
          on ( fmifiit~bukrs = bkpf~bukrs and
               fmifiit~kngjahr = bkpf~gjahr and
               fmifiit~knbelnr = bkpf~belnr )
          where fmifiit~knbelnr in s_belnr
            and fmifiit~bukrs = p_bukrs
            and fmifiit~kngjahr = p_gjahr
            and ( fmifiit~wrttp = '54' or
                  fmifiit~wrttp = '57' or
                  fmifiit~wrttp = '66' )
            and bkpf~bukrs = p_bukrs
            and bkpf~gjahr = p_gjahr
            and bkpf~belnr in s_belnr
            and bkpf~budat in s_budat
            and ( bkpf~bstat = 'V' or bkpf~bstat = 'W' or bkpf~bstat = 'Z' )
          group by fmifiit~knbelnr
                   bkpf~bstat
          order by fmifiit~knbelnr.
    Rob

  • Selecting both a aggregate function and another field

    I am trying to do something very simple but I am not sure of the syntax.
    I would like to select all of the petid's and find the count of the pets in a given city, both from the same table, Pets.
    Can somebody please help me with this?
    Thanks

    Hi,
    An aggregate function will give you one row of output per group.
    For example, if you use the aggregate COUNT function to get the total number of rows in a whole table, then you can only have one row of output, representing the whole table, so, if I understand the problem, you can't (easily) use an aggregate function.
    Almost all of the aggregate functions have analytic counterparts, that can produce the same results without collapsing the result set into one row per group.
    I think this is what you requested:
    SELECT  petid
    ,       COUNT (*) OVER (PARTITION BY 1)  AS total_cnt
    FROM    pets
    WHERE   city    = 'Paris'  -- or whatever
    ;Sorry, I'm not at a database now, so I can't check, but I think you don't need the PARTITION BY clause, so you can also say:
    ,       COUNT (*) OVER ()  AS total_cntThe keyword OVER marks this as an analytic, rather than an aggregate, function.

  • Select Into statement in db function - query from granted schema table

    problem with "select into" in db function in 10.2
    There are two schemas. 'mdbdev' is the master database and 'devusr' is granted SELECT table access to execute queries in mdbdev schema.
    with devusr, in SQL, I'm able to execute the following query
    select wm_concat(strConcatedCountryList)
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <param?>
    order by country_name)
    but when I use the same query in function/procedure with "select into", the compilation failed with error *"table or view does not exist"*
    FUNCTION GETCOUNTRYLISTTOSHIP (SHIP_STATUS IN NUMBER)
    RETURN VARCHAR2
    IS
    var2CountryList VARCHAR2(1000);
    BEGIN
    select wm_concat(strConcatedCountryList) INTO var2CountryList
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <value of SHIP_STATUS>
    order by country_name);
    return var2CountryList;
    END;
    Please advise/help/hint :)

    David, Justine, Thank you. The facts from this forum post helped a lot to get the solution.
    The query helped a lot (select * from all_tab_privs_recd where owner = 'MDBDEV' and table_name = 'COUNTRY_MASTER").
    there was a grant using ???(donno wht DBA said) and no direct SELECT grant on that country_master to "devusr". grant command executed. Now, it works :)

  • Using an Aggregate Function in a Sub-SELECT

    Ok. I have this Sub-SELECT and I'd like to base my outside query based on the resyult set of my inner Sub-SELECT which contains an Aggregate function.
    Is that possible???
    Here's the Query...
    SELECT *
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDTH
    INNER JOIN (SELECT CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll,
    MAX(CPMPNDT2.dt_billed_by_css)
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDT2
    WHERE CPMPNDT2.ky_pnd_seq_trans IN (6544937)
    GROUP BY CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll) DERIVE1
    ON CPMPNDTH.id_ba_esco = DERIVE1.id_ba_esco
    AND CPMPNDTH.ky_ba = DERIVE1.ky_ba
    AND CPMPNDTH.ky_enroll = DERIVE1.ky_enroll
    AND CPMPNDTH.dt_billed_by_css = ????DERIVE1.MAX(CPMPNDT2.dt_billed_by_css)???
    How can I designate that last qualifier ????....
    PSULionRP

    You should give your aggregate function a column-alias as in:
    SELECT *
    FROM   custpro.cpm_pnd_tran_hdr cpmpndth
           INNER JOIN (SELECT   cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll,
                                Max(cpmpndt2.dt_billed_by_css) as XXX    -- ADDED THIS.
                       FROM     custpro.cpm_pnd_tran_hdr cpmpndt2
                       WHERE    cpmpndt2.ky_pnd_seq_trans IN (6544937)
                       GROUP BY cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll) derive1
             ON cpmpndth.id_ba_esco = derive1.id_ba_esco
                AND cpmpndth.ky_ba = derive1.ky_ba
                AND cpmpndth.ky_enroll = derive1.ky_enroll
                AND cpmpndth.dt_billed_by_css = derive1.XXX
    /

  • Aggregate functions and normal function in SELECT statement

    hi
    i am using MS Access DataBase ...
    i have lot of integer coloumns in my Database
    i want to retrieve the coloumn values as well as the min , max and avg of that coloumn
    i dont know whether its possible to do in a single statement or not
    generally if we retrieve the values of a particular coloum
    we say " SELECT length FROM TABLENAME WHERE somecondition"
    and then get the values as int len = rs.getInt("length")..... over a loop
    but how to retieve the value of an aggregate function?
    like if i say "SELECT avg(colname),max(colname),min(colname) FROM TABLENAME WHERE somecondition"
    how do i retrieve this value ???
    i dont know if its possible or not ....pls help.........

    Give names too each column
    SELECT avg(colname) average,max(colname) max,....
    and then rs.getInt("average")
    This works in Oracle and Sybase, not sure on MS access tough

  • Oracle Function with a select into problem

    Here is one that I cannot figure out. I'm trying to select the median of a set of events in a purchase qty. I have the selects working in SQL. It returns the correct answer for several sets of test data. However, when I put this into a function to be able to call during more complex queries it doesn't work. I've tested the function several different ways and it's looking like the select median into v_median2... is not working. Please help!
    Here is the code... When this is run what ever is in v_plant is returned. IE: If you pass 1122 into with getmedian('4567','12345678-0001') this returns 4567 at the output. I've bypassed the v_plant and v_material in the select part below and it still output 4567.
    If you run the select (with test data put in place of v_plant and v_material in a sqlplus window without the INTO v_median2) it would return a 12.
    If you run this function as is it would return 4567.
    Here is the output from the dbms_output tests.
    4567
    12345678-0001
    4567
    12345678-0001
    4567
    WHY?
    CREATE OR REPLACE FUNCTION getmedian(v_plant IN VARCHAR2, v_material IN VARCHAR2)
    RETURN NUMBER
    AS
    v_median2 NUMBER;
    BEGIN
    DBMS_OUTPUT.PUT_LINE(v_plant);
    DBMS_OUTPUT.PUT_LINE(v_material);
    SELECT MEDIAN INTO v_median2
    FROM (SELECT ROWNUM as rownums,MEDIAN
    FROM (SELECT abs(quantity_in_unit_entry) AS MEDIAN
    FROM tbl_transactions
    WHERE plant = v_plant
    AND material = v_material
    AND movement_type IN ('961','261','201')
    ORDER BY quantity_in_unit_entry DESC))
    WHERE ROWNUMs = ( select round(COUNT(1)/2,0) AS TOTAL2
    from tbl_transactions t
    WHERE plant = v_plant
    AND material = v_material
    AND t.movement_type IN ('961','261','201'));
    DBMS_OUTPUT.PUT_LINE(v_plant);
    DBMS_OUTPUT.PUT_LINE(v_material);
    DBMS_OUTPUT.PUT_LINE(v_median2);
    RETURN v_median2;
    END;

    It looks like another one of those cases where the pl/sql engine doesn't yet handle everything that the sql engine does. The usual solution is to execute the part that only works in sql dynamically. Try this:
    CREATE OR REPLACE FUNCTION getmedian
      (v_plant    IN VARCHAR2,
       v_material IN VARCHAR2)
      RETURN         NUMBER
    AS
      v_rownums      NUMBER          := 0;
      v_sql          VARCHAR2 (4000) := NULL;
      v_median2      NUMBER          := 0;
    BEGIN
      SELECT ROUND (COUNT (1) / 2, 0)
      INTO   v_rownums
      FROM   tbl_transactions
      WHERE  plant = v_plant
      AND    material = v_material
      AND    movement_type IN
             ('961', '261', '201');
      v_sql :=
      'SELECT median
       FROM   (SELECT ROWNUM AS rownums,
                      median
               FROM   (SELECT   ABS (quantity_in_unit_entry)
                                    AS median
                       FROM     tbl_transactions
                       WHERE    plant = :v_plant
                       AND      material = :v_material
                       AND      movement_type IN
                                (''961'', ''261'', ''201'')
                       ORDER BY quantity_in_unit_entry DESC))
       WHERE  rownums = :v_rownums';
      EXECUTE IMMEDIATE v_sql INTO v_median2
      USING v_plant, v_material, v_rownums;
      RETURN v_median2;
    END getmedian;

  • How to use aggregate functions into Analytical functions

    Can we use aggregate functions into analytical functions?
    Please provide one example.
    Smiles.

    HI Learner6
    for information:
    Aggregate Functions
    Analytic Functions
    for practic:
    ORACLE-BASE - Analytic Functions
    Thank you

  • Using select * into within a function

    What I'm wanting to do is to have a select query with many select fields and automatically create a new table (with the same schema) and insert the select result set in this new table.
    I can't seem to figure it out and doing the EXECUTE 'select * into dest_table from orig_table'; wouldn't work (not implemented yet).
    One reason I would like to do it this way is because the field attributes of orig_table may be different from one client to another.
    Thanks for any advice.

    Thanks very much.
    When I tried the execute immediate '...'; in the function I got an error stating: 'type "immediate" does not exist
    I tried to do some research on 'execute immediate' to see what might be the problem but couldn't find anything substantial to my cause.
    I just installed postgreSQL 8.2 this afternoon, and took all the installation defaults, so it may be something I need to configure.
    Anways, however, I just took the actual sql from the execute immediate call and that worked for me.
    Are there any pitfalls to doing it that way.
    Again, thanks for your quick and helpful reply.

  • Aggregate functions for internal table.

    Hi Gurus,
    I'm just wondering whether we can use aggregate functions for internal table. I wanted to know the max value for a particular column in my internal table. How can I achieve this easily and quickly.
    Thanks,
    David.

    sort the table on which you want the maximum value and read it. Please find below example code.
    TYPES : BEGIN OF ty_mvke,
            matnr TYPE mvke-matnr,
            vkorg TYPE mvke-vkorg,
            vtweg TYPE mvke-vtweg,
           AUMNG type mvke-AUMNG,
            END OF ty_mvke.
    DATA : wa_mvke TYPE ty_mvke,
           it_mvke TYPE STANDARD TABLE OF ty_mvke.
    data : temp_AUMNG type AUMNG.
    START-OF-SELECTION.
      SELECT matnr vkorg vtweg AUMNG FROM mvke INTO
            table it_mvke.
    sort it_mvke by AUMNG.
    read TABLE it_mvke into wa_mvke INDEX 1.
    if sy-subrc = 0.
    move wa_mvke-AUMNG to temp_AUMNG.
    write : temp_AUMNG.
    endif.
    Thanks,
    Sreekala.

  • Problem with SELECT INTO Query

    Why am I always getting 0 for returnvalue in the following query?
    create or replace
    PACKAGE BODY MyPKG AS
    PROCEDURE SelectCount
       returnvalue       OUT      INTEGER
    AS
      BEGIN
    select COUNT(*) from MyTable into returnvalue;
    IF( SQL%ROWCOUNT >= 1 )
      THEN
        returnvalue := 1;
      ELSE
        returnvalue := 0;
      END IF; 
    dbms_output.put_line('returnvalue: ' || returnvalue);
    END SelectCount;
    END MyPKG ;

    Hi,
    When you use an aggregate function, such as COUNT, without a GROUP BY clause, then the query is guaranteed to return exactly 1 row, regadless of whether there are any rows in the table or not.
    Perhaps you meant:
    create or replace
    PACKAGE BODY MyPKG AS
    PROCEDURE SelectCount
       returnvalue       OUT      INTEGER
    AS
      BEGIN
          select COUNT(*) from MyTable into returnvalue;
          dbms_output.put_line('returnvalue: ' || returnvalue);
      END SelectCount;
    END MyPKG ;
    that is, simply lose the IF block.

Maybe you are looking for

  • Can two users work on different files of the same project?

    Sorry if this has been asked already...but can two users work on different files of the same project? How would that work? Would it work something like this? 1. From RoboHelp 7, user A checks out the entire project. 2. User A checks in the files they

  • I have win 7 pro and the download for jre 7u10 does not work on Firefox17, I have installed and uninstalled, but works on internet explorer.

    I have uninstalled jre7u10, the latest version of java, and re-installed this several times and it will NOT work on Firefox 17. I have checked that the plugins are downloaded in the add-ons tab and made sure they are Enabled. I have tried disabling e

  • Best practice for consuming web services

    Hi we are consuming web service in orchestration by "Add Generated Item".By using this option it creates 1 orch,1xsd file and some bindings. we have different projects for schemas,maps and orchestration under our solution in visual studio. Now i need

  • Payment term is changing automatically

    hi, Payment terms entered in Vendor master. Once we process the PO with same payment term it is fine. At the time of MIRO, if we select purchase order number, system is picking the payment term from PO. But if we process MIRO through delivery challan

  • Finder "browse..." window

    Hi all, I am relatively new to the Mac platform, and I have a bit of a problem. I set my Finder view options to "columns" and the arrange to "by kind", but whenever the "browse..." window opens (e.g. "save to..." in mail, or "download linked file as.