Analytic Function - Return 2 values

I am sure I need to use an analytic function to do this, I just cannot seem to get it right. I appreciate the help.
Table and insert statements:
create table TST_CK
DOC_ID NUMBER(6)      not null,
ROW_SEQ_NBR NUMBER(6) not null,
IND_VALUE VARCHAR2(2) null
INSERT INTO TST_CK VALUES ('1','6',NULL);
INSERT INTO TST_CK VALUES ('1','5',NULL);
INSERT INTO TST_CK VALUES ('1','4','T');
INSERT INTO TST_CK VALUES ('1','3','R');
INSERT INTO TST_CK VALUES ('1','9',NULL);
INSERT INTO TST_CK VALUES ('1','10',NULL);
INSERT INTO TST_CK VALUES ('1','7','T');
INSERT INTO TST_CK VALUES ('1','8','R');
INSERT INTO TST_CK VALUES ('2','1',NULL);
INSERT INTO TST_CK VALUES ('2','2',NULL);
INSERT INTO TST_CK VALUES ('2','3','T');
INSERT INTO TST_CK VALUES ('2','4','R');
INSERT INTO TST_CK VALUES ('2','5',NULL);
INSERT INTO TST_CK VALUES ('2','6',NULL);
INSERT INTO TST_CK VALUES ('2','7','T');
INSERT INTO TST_CK VALUES ('2','8','R');
INSERT INTO TST_CK VALUES ('4','1',NULL);
INSERT INTO TST_CK VALUES ('4','2',NULL);
INSERT INTO TST_CK VALUES ('4','3','X1');
INSERT INTO TST_CK VALUES ('4','4',NULL);
INSERT INTO TST_CK VALUES ('4','5',NULL);
INSERT INTO TST_CK VALUES ('4','6',NULL);
INSERT INTO TST_CK VALUES ('4','7','T');
INSERT INTO TST_CK VALUES ('4','8','R');
INSERT INTO TST_CK VALUES ('4','9',NULL);
INSERT INTO TST_CK VALUES ('4','10',NULL);
INSERT INTO TST_CK VALUES ('4','11',NULL);
INSERT INTO TST_CK VALUES ('4','12',NULL);
INSERT INTO TST_CK VALUES ('4','13','T');
INSERT INTO TST_CK VALUES ('4','14','R');
INSERT INTO TST_CK VALUES ('4','15',NULL);
INSERT INTO TST_CK VALUES ('4','16',NULL);
COMMIT;Here is what I have tried that gets me close:
SELECT MAX (TST_CK.DOC_ID), MAX (TST_CK.ROW_SEQ_NBR), TST_CK.IND_VALUE
  FROM ASAP.TST_CK TST_CK
WHERE (TST_CK.IND_VALUE IS NOT NULL)
GROUP BY TST_CK.IND_VALUE
ORDER BY 2 ASCHere is my desired result:
CV_1      CV_2
T           ROr even better result would be:
concat(CV_1,CV_2)With result:
T,RThanks for looking
G

Hi,
I am sure I need to use an analytic function to do this, I just cannot seem to get it right. I appreciate the help.
Table and insert statements: ...Thanks for posting the CREATE TABLE and INSERT statements.
Don't forget to explain how you get the results you want from that sample data.
GMoney wrote:
create table TST_CK
DOC_ID NUMBER(6)      not null,
ROW_SEQ_NBR NUMBER(6) not null,
IND_VALUE VARCHAR2(2) null
INSERT INTO TST_CK VALUES ('1','6',NULL);
If doc_id and row_seq_nbr are NUMBERs, why are you inserting VARCHAR2 values, such as '1' and '6' (in single-quotes)?
Here is my desired result:
CV_1      CV_2
T           ROr even better result would be:
concat(CV_1,CV_2)With result:
T,R
The results from the query you posted are:
MAX(TST_CK.DOC_ID) MAX(TST_CK.ROW_SEQ_NBR) IN
                 4                       3 X1
                 4                      13 T
                 4                      14 RWhat do the desired results represent?
Why do your desired results include 'R' and 'T', but not 'X1'? Why do you want
'T,R'     and not
'X1,T,R'     or
'X1,T'     or
'T,X1'     or something else?
Whatever your reasons are, there's a good chance you'll want to use String Aggregation . Your Oracle version is always important, but it's especially important in string aggregation problems, because some helpful new functions have beeen added in recent versions. Always say which version of Oracle (e.g., 11.2.0.3.0) you're using.

Similar Messages

  • Unable to see function return values in Visual Studio 2013 debugger

    Hi!
    I can't see function return values in
    Microsoft Visual Studio Ultimate 2013
    Version 12.0.31101.00 Update 4
    Microsoft .NET Framework
    Version 4.5.51650
    Installed Version: Ultimate<o:p></o:p>
    as described in  http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx
    So what can I do to get this functionality back?
    MsdnMezzo

    Hi MsdnMezzo,
    Reference:
    http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx
    If use the same sample in the above blog provided by you, how about the result? Could you debug it with the same steps? I could debug it in my side using the VS2013.
    So to make sure that whether it is your VS IDE issue, please debug it with this sample, if it works well, I doubt that we would think about your specific project and the debugging steps.
    If so, to really repro this issue, could you share us a sample with one drive? You could upload your project to one drive and share us the downloaded link in your new reply, I will download and repro this issue in my side.
    Best Regards,
    Jack
    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.

  • Function return value == -10. Native error code -2146824584 ADOBD.Recordset: Operation is not allowed when object is closed

    I want to call Stored Procedure that return records and output parameter, from CVI
    I can get output parrameter but when I want to get records stream I recieve following wrror:
    function return value == -10. Native error code -2146824584 ADOBD.Recordset: Operation is not allowed when object is closed

    in Stored procedure I create table variable and and insert into string values
    when I remove usage of table variable the error desappear

  • Group by on Function return value

    Dear All
    I'm facing a problem with when I have a group by on the return value of a function.
    Following is the scenario.
    Im having the following select query which executes in less than millisec for more than 20k records.
    SELECT T1.FIELD1,T1.FIELD2, MY_FUNCTION(T1.FIELD2) FROM TABLE T1 ;
    But when I modify the above query in the following way for the same number of records, the performance is going down to more than 4 mts.
    SELECT T1.FIELD1,T1.FIELD2, MY_FUNCTION(T1.FIELD2)FIELD3 FROM TABLE T1 GROUP BY T1.FIELD1,T1.FIELD3;
    can any one please suggest me whats the best solution in this regard.
    Thanks in advance
    Narayanan

    SQL> create or replace function get_sub(a varchar2)
      2  return varchar2
      3  is
      4  begin
      5   return substr(a,1,1);
      6  end;
      7  /
    Function created.
    SQL> select deptno, get_sub(ename) sub from emp;
        DEPTNO S
            20 S
            30 A
            30 W
            20 J
            30 M
            30 B
            10 C
            20 S
            10 K
            30 T
            20 A
            30 J
            20 F
            10 M
    14 rows selected.
    SQL> select deptno, get_sub(ename) sub, count(1)
      2  from emp
      3  group by deptno, get_sub(ename)
      4  /
        DEPTNO S   COUNT(1)
            10 C          1
            10 K          1
            10 M          1
            20 A          1
            20 F          1
            20 J          1
            20 S          2
            30 A          1
            30 B          1
            30 J          1
            30 M          1
            30 T          1
            30 W          1
    13 rows selected.Rgds.
    Everything which is not affected by aggregate functions
    should be included into GROUP BY. And GROUP BY can't use
    aliases but expressions only.
    You have to think what exactly do you want to get
    for FIELD02 - do you want get max/min/avg/count ?
    Message was edited by:
    dnikiforov
    (I'm asking because your query probably should look like
    SELECT T1.FIELD1,T1.FIELD2, MY_FUNCTION(T1.FIELD2) FIELD3 FROM TABLE T1 GROUP BY T1.FIELD1,T1.FIELD2
    Message was edited by:
    dnikiforov

  • Data Services Designer - Function returns value, but doesnt always populate

    Within my Query Transform I call a function that I pass a old Vendor code to a sql statement and it does a few lookups and cross references it returns a new value. My issue is sometime it doesnt put the value in the field. I know it has returned a value as I had the funtion print it out for me, so I can see the value that was passed and the returning value, but when I look in my table there is no value.
    I have added the function call for you to see it is very simple takes one parameter, I have also added the print out from my function, does anyone have any ideas??
    (This is under the field Vendor Code)
    P2CMM05_Look_UP_Vendor_Code(Query.LIFNR)
    6088     4800     PRINTFN     6/28/2011 9:27:48 AM     @@@@@@@@@@@ Ret_Vendor_code @@@@@@@@@@@   MCI_719
    6088     4800     PRINTFN     6/28/2011 9:27:48 AM     @@@@@@@@@@@ $Vendor_code @@@@@@@@@@@    MUR_51

    Within my Query Transform I call a function that I pass a old Vendor code to a sql statement and it does a few lookups and cross references it returns a new value. My issue is sometime it doesnt put the value in the field. I know it has returned a value as I had the funtion print it out for me, so I can see the value that was passed and the returning value, but when I look in my table there is no value.
    I have added the function call for you to see it is very simple takes one parameter, I have also added the print out from my function, does anyone have any ideas??
    (This is under the field Vendor Code)
    P2CMM05_Look_UP_Vendor_Code(Query.LIFNR)
    6088     4800     PRINTFN     6/28/2011 9:27:48 AM     @@@@@@@@@@@ $Vendor_code @@@@@@@@@@@    MUR_51
    6088     4800     PRINTFN     6/28/2011 9:27:48 AM     @@@@@@@@@@@ Ret_Vendor_code @@@@@@@@@@@   MCI_719

  • How to get a stored function return value (which is not a cursor)?

    I want to do so with ADO inside Visual Basic. I know how to call a stored procedure, but nothing I tried could help me in calling a stored function and getting its return code. Note that the function has no cursors within its argument or return code.
    Your quick response would be appreciated
    Eyal

    Eyal,
    A stored function returns a value. You need to have the first parameter (of correct data type) for the returned value. The parameter binding is pretty much the same as you would do with stored procedures.
    e.g. "begin :1= proc(....); end;"
    Sinclair

  • How can i pass function return values in to varray

    Hi
    create procedure name(parameters list)
    here ---i am calling a function
    varname := function name
    returns 4 values
    My doudt is how can i pass these return values in to varray..
    Type varray vname[5] date type
    Begin
    statements
    end prodedure name;
    pls clarify me its urgent

    This may give u a start
    sql>
    create or replace package test_array_pack as
    type ar1 is varray(10) of number;
    end;
    Package created.
    sql>
    create or replace function test_array return test_array_pack.ar1 is
      v_ar1 test_array_pack.ar1;
    begin
    v_ar1 := test_array_pack.ar1(1,2,3,4);
    return v_ar1;
    end;
    Function created.
    sql>
    declare
    v_ar2 test_array_pack.ar1;
    begin
    v_ar2 := test_array;
    end;
    PL/SQL procedure successfully completed
    Message was edited by:
            jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • ExtendScript function return values

    As far as I can tell, it's only possible to run ExtendScript functions from a CS Extension. I don't see any (straight-forward) way get the return value of an ExtendScript function.
    CSXSInterface.getInstance().evalScript() does not seem to return any useful information. Am I missing something, or should I make a feature request?
    Harbs

    I must be doing something wrong, because it's still not working...
    Here's my ExtendScript:
    function test1(){
    alert(1);
    return "bla bla";
    function test2(){
    alert(2);
        return{
            text:"bla bla",
            number:1
    function test3(){
    alert(3);
        return
            <bla>
                <ble/>
                <ble>
                    <blu/>
                </ble>
            </bla>
    Here's my ActionScript:
                var result1:SyncRequestResult = CSXSInterface.getInstance().evalScript("test1");
                var result2:SyncRequestResult = CSXSInterface.getInstance().evalScript("test2");
                var result3:SyncRequestResult = CSXSInterface.getInstance().evalScript("test3");
    and here's what I'm seeing in the debugger:
    I am getting all three alerts, so I know that the functions are being run...
    Harbs

  • FDM Lookup function returning value not = the current POV

    Is anyone having problems returning values for periods other than current POV.
    "The FDM Lookup function is used to return the value of any source account that resides in FDM.
    The function can be used within a logic function or a logic expression."
    Presently I can only return value in current POV.
    If anyone can return a source account value from a period other than the current POV let me know.
    Tom Peera
    Syntax
    | , , 02/28/2011 , 1535-000-000 |

    Here is the dirty fix, I'm heading off to sleep.
    If the function CurrentAdId doesn't return a number, then
    this will ensure it returns 0 (prevents your error, may not display
    an ad):
    <CFFUNCTION
    NAME="CurrentAdId"
    ACCESS="Private"
    RETURNTYPE="numeric"
    HINT="For internal use. Returns the Id of the current ad in
    rotation.">
    <!--- Return the adId from the current row of the
    GetAdIds query --->
    <cfset var returnVal = ListGetAt(THIS.AdList,
    THIS.CurrentListPos)>
    <cfif NOT IsNumeric(returnVal)>
    <cfset returnVal = 0>
    </cfif>
    <CFRETURN returnVal>
    </CFFUNCTION>

  • REF CURSOR? FUNCTION RETURN VALUE BASED ON DYN QUERY

    Hi to all,
    i need to write a function that do the following (but have to work...):
    Note: what i really don't remember is how can i have a valid cursor based using
    a dynamic field taken from the input value PAR_NAME.
    Hope that my problem is clear reading the NOT WORKING CODE below.
    thanx a lot
    CREATE OR REPLACE
    FUNCTION FNC_RET_FLD_VAL(ID_CNT NUMBER, PAR_NAME VARCHAR2) RETURN VARCHAR2 AS
    RETVAL VARCHAR2(300);
    CURSOR FVAL IS
    SELECT PAR_NAME FROM TBCONTATTI WHERE NORECORD=ID_CNT;
    BEGIN
    FOR REC IN FVAL LOOP
    RETVAL:=REC.PAR_NAME;
    END LOOP;
    RETURN RETVAL;
    END FNC_RET_FLD_VAL;

    Like this ?
    SQL> create function get_data(colname varchar2, empno number)
      2  return varchar2
      3  is
      4   ret varchar2(4000);
      5  begin
      6   begin
      7    execute immediate 'select ' || colname || ' from emp where empno = :1' into ret using empno;
      8   exception
      9    when no_data_found then
    10     ret := null;
    11   end;
    12   return ret;
    13  end;
    14  /
    Function created.
    SQL> select get_data('ename',7369) from dual;
    GET_DATA('ENAME',7369)
    SMITH
    SQL> select get_data('job',7369) from dual;
    GET_DATA('JOB',7369)
    CLERK
    SQL> select get_data('job',-1) from dual;
    GET_DATA('JOB',-1)
    Rgds.

  • Can pipelined functions' return values be used in WHERE clause?

    If I have function MY_FUNC that returns a REFCURSOR with columns COL1, COL2, COL3
    can I use the values returned in the output cursor in my WHERE clause as well as in the SELECT clause?
    e.g.
    SELECT COL1, COL2, COL3
    FROM TABLE(MY_FUNC(param1, param2))
    WHERE COL1 = 24 AND COL2=25
    Would that be proper SQL?

    Hi,
    SQL> Create OR Replace Package Pkg_Test_ Is
      2 
      3     Type my_typ Is Table Of Number;
      4 
      5     Function fnc_test Return my_typ Pipelined;
      6 
      7  End;
      8  /
    Package created
    SQL> Create OR Replace Package Body Pkg_Test_ Is
      2 
      3     Function fnc_test Return my_typ
      4        Pipelined Is
      5        va_typ my_typ := my_typ();
      6     Begin
      7        For i IN 1 .. 10 Loop
      8           va_typ.Extend;
      9           va_typ(va_typ.Count) := i;
    10           Pipe Row(va_typ(va_typ.Count));
    11        End Loop;
    12        Return;
    13     End;
    14 
    15  End;
    16  /
    Package body created
    SQL> SELECT *
      2    FROM Table(PKG_TEST_.FNC_TEST)
      3   WHERE COLUMN_VALUE > 5
      4  /
    COLUMN_VALUE
               6
               7
               8
               9
              10Regards,
    Christian Balz

  • Problem with return value of stored function

    Hi,
    I've made a stored function that insert a new row in a table and return the primary key (see at the end of the message the function script).
    In VS 2005 with Visual basic, using the designer, I've created a dataset containing a tableAdapter to be able to use the Pl/SQL function.
    My problem is I can't get the proper return value. The VB code below works without error except that I get 0 as value.
    What's wrong?
    Cheers,
    Sebastien
    VB code
    Dim myAddSession As New ICISDataSetTableAdapters.AddSessionTableAdapter
    Dim intSessionId As Integer
    intSessionId = myAddSession.ADD_SESSION(tbxUsername.Text, _
    tempFolder.Substring(tempFolder.LastIndexOf("\") + 1), _
    "toto", Environment.GetEnvironmentVariable("COMPUTERNAME"), _
    myLevelAccess.icisUserId, myLevelAccess.levelId)
    The debugger tells me that the ADD_SESSION function return value is Object.
    add_session PL/SQL script:
    CREATE OR REPLACE FUNCTION ICISSEC.add_session (
    orausername IN icis_session.ora_user_name%TYPE,
    ctxsessionid IN icis_session.ctx_session_id%TYPE,
    ctxsessionname IN icis_session.ctx_session_name%TYPE,
    ctxservername IN icis_session.ctx_server_name%TYPE,
    icisuserid IN icis_session.icis_user_id%TYPE,
    startlevelid IN icis_session.start_lvl_id%TYPE
    RETURN icis_session.ICIS_SESSION_ID%TYPE
    IS
    tmpvar icis_session.ICIS_SESSION_ID%TYPE;
    BEGIN
    INSERT INTO icis_session
    (ora_user_name, ctx_session_id, ctx_server_name,
    icis_user_id, start_lvl_id, ctx_session_name
    VALUES (orausername, ctxsessionid, ctxservername,
    icisuserid, startlevelid, ctxsessionname
    RETURNING icis_session_id
    INTO tmpvar;
    COMMIT;
    RETURN tmpvar;
    EXCEPTION
    WHEN OTHERS
    THEN
    RAISE;
    END add_session;

    naama wrote:
    that if a value is null to convert it to 0 ? . i mean in the part of the declaration of parameter
    Nope, can't do that in the signature. You'll need to handle that by validating the passed parameters at the start of the function.
    It's simple enough. In your case you might just as well test for NULL and fail the function like this:
        FUNCTION date_post_message(
                user_lock_in IN NUMBER,
                form_type_in IN NUMBER DEFAULT 0 ,
                date_in      IN DATE)
            RETURN BOOLEAN
        IS
            v_num NUMBER(1);
        BEGIN
            dbms_output.put_line('Value of parameters : user_lock_in : '||user_lock_in || ' : form_type_in : '||form_type_in||' : date_in : '||date_in );
            IF user_lock_in = 1 THEN
                RETURN FALSE;
            END IF;
            IF form_type_in IS NULL THEN
                RETURN FALSE;
            ELSIF form_type_in NOT IN (1,2) THEN
                RETURN FALSE;
            END IF;
            RETURN TRUE;
        EXCEPTION
        WHEN NO_DATA_FOUND THEN
            RETURN FALSE;
        END;In other use cases I would declare a local variable and process it like this:
            IF form_type_in IS NULL THEN
                l_form_type := 0;
            ELSE
                 l_form_type := form_type_in;
            END IF;Obviously the code should use the local variable rather than the parameter.
    Validating the values passed in parameters at the start of a function is good practice. If you really want to go to town, read about Design By Contract.
    Cheers, APC
    Edited by: APC on Nov 9, 2011 1:36 PM
    Added example, as requested by OP

  • Analytic Function partition by

    I am almost where I want to be with this but lat steps are always killer.
    I have a query that returns a list of ETL mappings/packages. The Source package (first one) can be identified with an ‘@’ in the string and all packages related to that mapping will follow (sorted by time).
    I am stuck trying to propogate the name of this Source Mapping to all the packages below it until a change to the next Source.
    Here’s an example of what I want
    Source               Grp          Name
    “sales@source”     1          Sales
    salesa               0          Sales
    slsb               0          Sales
    “orders@hth”     1          Orders
    ordersa          0          Orders
    ordb               0          Orders
    ordersc          0          Orders
    “inventory@...     “ 1          Inventory
    So my sql is basically showing how I am using Lag but it’s coming up short since I have to pre-determine the offset, which won’t work in this case.
    SELECT source,
    CASE WHEN source LIKE '%@%' THEN 1 ELSE 0 END GRP,
    CASE WHEN
    (CASE WHEN source LIKE '%@%' THEN 1 ELSE 0 END) =1
    THEN substr (map_primary_source, 2, (instr(map_primary_source, '@')-3))
    ELSE
    lag(substr (map_primary_source, 2, (instr(map_primary_source, '@')-3)), 1,0)
    over (ORDER BY creation_date)
    END NAME,
    creation_date
    FROM table
    WHERE creation_date > SYSDATE -1
    ORDER BY creation_date
    I’ve been trying different flavors of analytical functions (first value, over partition by, etc) but am coming up short.
    By the way I am on 8.x

    Yes, it works for variable numbers of rows.
    Here is how to make your grp column and the solution all in one:
    CREATE TABLE test AS (
        SELECT 'THIS@DESC' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'THISa' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'THISb' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'THISc' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'THISd' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'THISe' description, 'SALES' group_name FROM DUAL
        UNION
        SELECT 'DEMO@DESC' description, 'DEMO' group_name FROM DUAL
        UNION
        SELECT 'DEMOa' description, 'DEMO' group_name FROM DUAL
        UNION
        SELECT 'DEMOb' description, 'DEMO' group_name FROM DUAL
        UNION
        SELECT 'THAT@DESC' description, 'THAT' group_name FROM DUAL
        UNION
        SELECT 'THATa' description, 'THAT' group_name FROM DUAL
        UNION
        SELECT 'THATb' description, 'THAT' group_name FROM DUAL
        UNION
        SELECT 'THATc' description, 'THAT' group_name FROM DUAL
        UNION
        SELECT 'WHERE@DESC' description, 'WHERE' group_name FROM DUAL
        UNION
        SELECT 'WHEREa' description, 'WHERE' group_name FROM DUAL
    Table created.
    SELECT * FROM test
    DESCRIPTIO GROUP
    DEMO@DESC  DEMO
    DEMOa      DEMO
    DEMOb      DEMO
    THAT@DESC  THAT
    THATa      THAT
    THATb      THAT
    THATc      THAT
    THIS@DESC  SALES
    THISa      SALES
    THISb      SALES
    THISc      SALES
    THISd      SALES
    THISe      SALES
    WHERE@DESC WHERE
    WHEREa     WHERE
    SELECT
       FIRST_VALUE(description) OVER (PARTITION BY group_name ORDER BY group_num DESC) description,
       group_name
    FROM
        SELECT
           description,
           CASE
              WHEN
                 INSTR(description, '@') > 0
              THEN
                 1
              ELSE
                 0
           END group_num,
           group_name
        FROM
           test
    DESCRIPTIO GROUP
    DEMO@DESC  DEMO
    DEMO@DESC  DEMO
    DEMO@DESC  DEMO
    THIS@DESC  SALES
    THIS@DESC  SALES
    THIS@DESC  SALES
    THIS@DESC  SALES
    THIS@DESC  SALES
    THIS@DESC  SALES
    THAT@DESC  THAT
    THAT@DESC  THAT
    THAT@DESC  THAT
    THAT@DESC  THAT
    WHERE@DESC WHERE
    WHERE@DESC WHERE

  • Execution flow doesn't wait for return values

    I have created JNI wrappers for existing dlls. However I'm getting weird behavior. My Java function calls a c function which communicates with an old mainframe. If I retrieve one row at a time its fine but if I do a loop the virtual machine crashes. Sometimes, if I add an empty loop for (30000 iterations) then its fine. Its like java is already trying to retrieve the next row while the first row is still being printed on my screen. I've tried adding synchronized in case the dlls where multi-threaded but it has not made a difference. Is there any way to control the execution flow so that it can't go to the next line until the values are truly returned from the c dll.
    thanks
    MA

    There are many function being called on the native side. Since I didn't want to modify the native side
    (because the old dlls are used by another application), I added my own dll as an intermediary between the old c dlls and the java side.
    To fix the problem I am having, I've heard of another project where the native side would write the returned values to a file and only once the file is written can the Java side continue. Is this the only way to control the execution flow?
    Right now I have about 5 empty loops which run to 100000 and things work most of the time. But I would prefer to find a way to say wait until the values are returned correctly.
    Essentially, what I'm doing is
    for (int i=1;i<10; i++){
       test.init(Integer.toString(i),Integer.toString(i),"english desc"+  Integer.toString(i),"french desc"+ Integer.toString(i));
       test.execute(test.ActionAdd);
    }This is supposed to add one row with four fields. I'm just putting junk for the test. If I call the two main lines
    test.init(Integer.toString(i),Integer.toString(i),"english desc"+  Integer.toString(i),"french desc"+ Integer.toString(i));
    test.execute(test.ActionAdd);just once it works fine but if I loop them then it crashes after a few loops. If I put a loop as shown below then it works fine. This is part of the code when I'm adding. Is it being looped 10 times from the code above.
    jsession.scanTable(table,errorlist);
                rtc = table.getRecordCount(errorlist);
                if (rtc > 0)
                publish(rtc+" records found.");
                    for(int i = 1; i <= rtc; ++i)
                        for (int j = 0; j < ElementName.size();j++)
                            publish((String)ElementName.get(j)+ ": " + table.getFieldByName((String)ElementName.get(j),i,errorlist));
                            for (int k = 0; k<100000;k++);
                else
                    publish("No records found.");
                }In the code, when the rows are added, I print them out just to make sure they were added correctly. This is where I got the idea that the Java code was not in synch with the native side because it would crash while writting out a line but it didn't happen every time at the same place.
    This is the function getFieldByName
    public String getFieldByName (String p_FieldName, int p_LineNum, ErrorList p_Errors)
              String retval = "";
              int ret;
              try
                   p_FieldName = prepareFieldName(p_FieldName);
                   retval = new String();
                   ret    = 0;
                   if (this.ptrTableView == NOT_SET)
                        p_Errors.addMessage(p_Errors.SEV_SYSTEM_ERROR(), "Table View Pointer not set");
                        throw (new Exception());
                   // allocating string buffer for value returned
                   StringBuffer m_FieldValue = new StringBuffer();
                   // determining length of value
                   int m_length[] = {0};
                   ret = gti.GetFieldLen(this.ptrTableView, p_FieldName, m_length, eb.getErrorBlockPtr());
                   if (m_length[0] == 0) m_length[0] = 100;
                   m_FieldValue = new StringBuffer(m_length[0]);
                   // get line field          
                   ret = gti.GetLineField(this.ptrTableView, p_FieldName, p_LineNum, m_FieldValue, eb.getErrorBlockPtr());           
                   if (ret != 0)
                          p_Errors.addMessage(p_Errors.SEV_ERROR(), "Error retrieving field value ("+p_FieldName+")");
                   else
                          retval = m_FieldValue.toString();
              catch (Throwable t)
                   p_Errors.addMessage(p_Errors.SEV_ERROR(), "Error retrieving field value ("+p_FieldName+")");
              return retval;
        }The main functions are
    GetFieldLen
    GetLineField
    They go to the native side through my dll which wraps the old dlls.
    Here are is one of the main functions in my dll. I also have the source for the functions they are calling but they are calling other functions which are calling other functions. There is a lot of code . Yes, they use arrays.
    JNIEXPORT jint JNICALL Java_advantagewrapperspk_GtiNative_GtiGetLineField
      (JNIEnv *env, jclass cls, jint p_tableViewPtr, jstring VIEWFIELDNAME, jint VIEWFIELDNUM, jobject VIEWFIELDVALUE, jint iErrBlockPtr)
           //printf("\n\nGtiGetLineField in C:\n");
           jint iResult = 0;
           char *temp1 = (*env)->GetStringUTFChars(env,VIEWFIELDNAME,0);
           char *temp2 = (*env)->GetStringUTFChars(env,VIEWFIELDVALUE,0);
         iResult = GtiGetLineField(p_tableViewPtr,temp1,VIEWFIELDNUM,temp2,iErrBlockPtr);
           //printf("VIEWFIELDNUM %d ",VIEWFIELDNUM);
           //printf("\ntemp1 %s ",temp1);
           //printf("\ntemp2 %s ",temp2);
         (*env)->ReleaseStringUTFChars(env,VIEWFIELDNAME,temp1);
         if (temp2 == 0)      return iResult;
        if (temp2 != NULL)
                cls = (*env)->GetObjectClass(env,VIEWFIELDVALUE);
                jmethodID mid = (*env)->GetMethodID (env,cls,"append","(Ljava/lang/String;)Ljava/lang/StringBuffer;");
                 if (mid == 0) return iResult;
                 jstring sfinal = (*env)->NewStringUTF (env, temp2);
                (*env)->CallObjectMethod(env,VIEWFIELDVALUE,mid,sfinal);
              if (VIEWFIELDVALUE != NULL) (*env)->ReleaseStringUTFChars(env,VIEWFIELDVALUE,temp2);
         //(*env)->ReleaseStringUTFChars(env,VIEWFIELDVALUE,temp2);
         return iResult;
      }This calls
    * Function Name : GtiGetLineField()
    * Description   : Retrieves the value of a line field in a table view
    * Parameters    : pTableViewPtr pTableView--the table view from which to
    *                                           retrieve the value of a line
    *                                           field
    *                 VIEWFIELDNAME szFieldName--the name of the line field
    *                                            whose value is returned
    *                 VIEWLINENUM iLineNum--number of line from which to retrieve
    *                                       field value.  Lines are numbered
    *                                       beginning with 1.
    *                 VIEWFIELDVALUE szFieldValue--returns the value of the
    *                                              line field
    *                 ErrBlockPtr sourceeb--error context info from calling
    *                                       function
    * Return values : int--returns RCT_RETURNOK, RCT_WARNCORECONNECT, or
    *                      RCT_FAILCORECONNECT
    * Modifications : REH - 05/25/93
    int GtiGetLineField ( TableViewPtr pTableView,
                          VIEWFIELDNAME szFieldName,
                          VIEWLINENUM iLineNum,
                          VIEWFIELDVALUE szFieldValue,
                          ErrBlockPtr sourceeb )
       int iRc ;      /* return code */
       ELOG_INIT( sourceeb,
                  "GtiGetLineField",
                  "retrieving the value of a line field in a table view" ) ;
       /* in Gti, we start numbering lines from 1, because that is the way a user
          sees them on the screen.  In Ldm, following C conventions, we start
          numbering lines at 0.  So in LdmSetField, we subtract 1 from iLineNum */
       iRc = LdmGetField( pTableView->pTran,
                          szFieldName,
                          szFieldValue,
                          iLineNum - 1,
                          0,                  /* map occurrence = 1 */
                          ELOG_ERRBLOCK ) ;
       /* in case Ldm returned a warning, indicate so to the calling function */
       iRc = ( iRc == LDM_RETURNOK ) ? RCT_RETURNOK : RCT_WARNCORECONNECT ;
       return( iRc ) ;
       /* if exception was raised, it was due to COREConnect */
       ELOG_END( RCT_FAILCORECONNECT ) ;
    }which calls
    /****************************** API Header *********************************\
    * API Name: LdmGetField
    * This function copies the string value of a specified FIELDNAME into a
    * buffer specified by FIELDVALUE.  The string is NULL terminated.
    * The first OCCUR determines which occurrence of the field in the map.
    * The second OCCUR determines which occurence of the map in the transaction
    * area.  Remember that occurrences are numbered like C arrays: a transaction
    * with ten occurrences of a field will have fields numbered zero through
    * nine.
    * It is assumed that FIELDVALUE has enough space to accommodate the field's
    * value.
    int LdmGetField( HTRAN       htran,
                     FIELDNAME   fieldname,
                     FIELDVALUE  fieldvalue,
                     FIELDOCCUR  fieldoccur,
                     MAPOCCUR    mapoccur,
                     ErrBlockPtr seb )
       ELOG_INIT ( seb, "LdmGetField", "getting transaction field value" ) ;
       if ( htran->Occurrence <= mapoccur ) {
          ElogFail1( LDM_FAILOCCNOTFOUND, htran->TranName ) ;
       }  /* END if. */
       /* Since 'blank' values for field or map occurrences are zero, there
          is no need to set a default. */
       LdmsGetField( htran->Map->CCMap,
                     htran->TranData,
                     fieldname,
                     fieldvalue,
                     fieldoccur,
                     mapoccur,
                     ELOG_ERRBLOCK ) ;
       return( LDM_RETURNOK ) ;
       ELOG_END ( ELOG_ERRBLOCK->Rc ) ;
    }  /* END LdmGetField. */which calls
    /****************************** API Header *********************************\
    * API Name: LdmsGetField
    * Put the value of FIELDNAME into FIELDVALUE.  The field must be an element
    * of the specified map.  The new value will be set in the specified data
    * buffer.  The occurrences refer to the occurrence of the field in the map
    * and the occurrence of the map in the data buffer.
    int LdmsGetField ( CCMapPtr    rcmap,
                       char        *dataarea,
                       FIELDNAME   fieldname,
                       FIELDVALUE  fieldvalue,
                       FIELDOCCUR  fieldoccur,
                       MAPOCCUR    mapoccur,
                       ErrBlockPtr seb )
       ElementPtr element ;
       char       *fieldoffset ;
       ELOG_INIT ( seb, "LdmsGetField", "getting a field of a map" ) ;
       /* Search the transaction definition area (map) for matching
          FIELDNAME. If found, copy FIELDVALUE to defined offset in
          transaction buffer. */
       element = LdmsFindField( rcmap, fieldname, fieldoccur, &localeb ) ;
       /* Copy the value from the transaction data area into FIELDVALUE. */
       fieldoffset = dataarea +
                     ( ( rcmap->BufferLength * mapoccur ) + element->Offset ) ;
       strncpy( fieldvalue, fieldoffset, element->Length ) ;
       fieldvalue[ element->Length ] = '\0' ;
       return( LDM_RETURNOK ) ;
       ELOG_END ( ELOG_ERRBLOCK->Rc ) ;
    }  /* END LdmsGetField. */and on it goes
    I gather from your question about arrays that they might be the source of the problem. Could it be that the pointer to the array is returned while the array is not completed? Any information would help. Thanks.

  • Select value of most occurances - analytical function?!

    Hi ...
    I've get stuck with a "little" problem.
    I try to provide some testing code for this:
    CREATE TABLE a1 (
         id NUMBER(8),
         val NUMBER(6),
         title VARCHAR2(16),
         CONSTRAINT test_pk PRIMARY KEY(id)
    INERT INTO a1 (id, val, title) VALUES (1,12,'c');
    INERT INTO a1 (id, val, title) VALUES (2,13,'b');
    INERT INTO a1 (id, val, title) VALUES (3,13,'a');
    INERT INTO a1 (id, val, title) VALUES (4,13,'a');
    INERT INTO a1 (id, val, title) VALUES (5,42,'a');
    INERT INTO a1 (id, val, title) VALUES (6,42,'b');
    INERT INTO a1 (id, val, title) VALUES (7,42,'b');Actually the table is much bigger ;) But this should be ok for this question. It already exist a query like:
    SELECT
         count(*) -- just an example
    FROM
         a1
    GROUP BY
         val
    -- should return 1,3,3 (for the groups val=12, val=13,val=42)Now it is nessecary to select a title for each group (specified by group by). And there the title which occurs the most in this group should be selected. For this example this are 'c' for the group val=12 .. 'a' for the group val=13 and finally 'b' for the group val=42.
    I tried to use some anayltical function, but I#m not able to get this to work - may be because I never used analytical functions before. If I try something I mostly get an error: Keyword FROM not at expected position (ORA-00923). I searched for some tutorial/howto documentations where my problem is handled but without success. So I guess the syntax and the way to understand analytical functions is not as easy as it semms to be ...
    title OVER ( ORDER BY count(*) ROWS | RANGE BETWEEN 1 AND 1 ) <-- that would by logical for my brain, but not for oracles ;-)
    Can somebody help?
    Thanks!

    Hi folks,
    thanks for the variuos answers! Weekend is over, so we should work on ...
    I tried some examples you gave me. And I decide to provide more detailes information! At first, if the amount of 'a' and 'b' is equal it doesn't matter which one will be returned (so it can be undefined, if that makes thing easier). I will now paste the original query I work with and I add some comments for you - so you can find the lines which should be changed to return the most occurances-value.
    If you think it makes sense to Provide some create-table ddl an (maybe as csv file) some data, tell me how i can do that (I think its not an option to post ~ Mio rows as Inserts here).
    The select-query I want to manipulate - this is no more related to our test-table 'a1' !! For Example let us look on the rows where 'A' and 'drm_' is selected - starts at line 7!
    SELECT
      box_id,
      schedule_id,
      fixsecs_down(MIN(acqtime),600),
      COUNT(*), -- each row in rfm_meas_hr represents one frame of measuremnt-data, so this represents the number of frames received in this block
      -- instead of 'A' the most occurance of the col 'rpro' should be selected here
      'A',
      -- like above, but from the column 'rdmo'
      'drm_',
      -- below this some other cols are calculated/selected, not important here
      FLOOR(MEDIAN(rfre)),
      ROUND(AVG(rdbv),2),
      ROUND(SUM(POWER(rdbv,2)),2),
      ROUND(MAX(rdbv),2),
      ROUND(MIN(rdbv),2),
      ROUND(SUM(rsnr)/SUM(nframes),2),
      ROUND(SUM(POWER(rsnr,2)),2),
      ROUND(MAX(rsnr),2),
      ROUND(MIN(rsnr),2),
      ROUND( AVG(rsta_sync),2), -- rsta_sync
      ROUND(SUM(POWER(rsta_sync,2)),2), -- rsta_sync_s
      ROUND( MIN(rsta_sync),2), -- rsta_sync_min
      ROUND( MAX(rsta_sync),2), -- rsta_sync_max
      ROUND( AVG(rsta_fac),2), -- rsta_facc
      ROUND(SUM(POWER(rsta_fac,2)),2), -- rsta_fac_s
      ROUND( MIN(rsta_fac),2), -- rsta_fac_min
      ROUND( MAX(rsta_fac),2), -- rsta_fac_max
      ROUND( AVG(rsta_sdc),2), -- rsta_sdc
      ROUND(SUM(POWER(rsta_sdc,2)),2), -- rsta_sdc_s
      ROUND( MIN(rsta_sdc),2), -- rsta_sdc_min
      ROUND( MAX(rsta_sdc),2), -- rsta_sdc_max
      ROUND( AVG(rsta_audio),2), -- rsta_audio
      ROUND(SUM(POWER(rsta_audio,2)),2), -- rsta_audio_s
      ROUND( MIN(rsta_audio),2), -- rsta_audio_min
      ROUND( MAX(rsta_audio),2), -- rsta_audio_max
      MIN(rser), TODO:  most occurances
      MIN(rtty_stream0), -- TODO:  most occurances
      MIN(rtty_stream1), -- TODO:  most occurances
      MIN(rtty_stream2), -- TODO:  most occurances
      MIN(rtty_stream3), -- TODO:  most occurances
      ROUND(AVG(NVL(rafs_error/nullif(rafs_au,0),1))*SUM(rafs_au)/NULLIF(SUM(rafs_au),0),2), -- rafs
      ROUND( SUM( POWER(  NVL(rafs_error/nullif(rafs_au,0),1),2))*SUM(rafs_au)/NULLIF(SUM(rafs_au),0) ,2), -- rafs_s
      ROUND(MIN(rafs_error/ NULLIF(rafs_au,0)),2), -- rafs_min
      ROUND(MAX(NVL(rafs_error/NULLIF(rafs_au,0),1) )*SUM(rafs_au)/NULLIF(SUM(rafs_au),0),2), -- rafs_max
      SUM(robm_A),
      SUM(robm_B),
      SUM(robm_C),
      SUM(robm_D),
      SUM(robm_E),
      ROUND(SUM(rwmf) / SUM(nframes),2), -- rwmf
      ROUND(SUM(POWER(rwmf,2)),2), -- rwmf_s
      ROUND(MIN(rwmf),2), -- rwmf_min
      ROUND(MAX(rwmf),2), -- rwmf_max
      ROUND(SUM(rwmm) / SUM(nframes),2), -- rwmm
      ROUND(SUM(POWER(rwmm,2)),2), -- rwmm_s
      ROUND(MIN(rwmm),2), -- rwmm_min
      ROUND(MAX(rwmm),2), -- rwmm_max
      ROUND(SUM(rmer) / SUM(nframes),2), -- rmer
      ROUND(SUM(POWER(rmer,2)),2), -- rmer_s
      ROUND(MIN(rmer),2), -- rmer_min
      ROUND(MAX(rmer),2), -- rmer_max
      ROUND(SUM(RBP0_ERRS+ RBP1_ERRS+ RBP2_ERRS+ RBP3_ERRS) / NULLIF(SUM(RBP0_BITS+ RBP1_BITS+ RBP2_BITS+ RBP3_BITS),0) ,10), -- ber
      ROUND(SUM(POWER( (RBP0_ERRS+ RBP1_ERRS+ RBP2_ERRS+ RBP3_ERRS) / NULLIF((RBP0_BITS+ RBP1_BITS+ RBP2_BITS+ RBP3_BITS),0) ,2)),10), -- ber_s
      ROUND(MIN(RBP0_ERRS+ RBP1_ERRS+ RBP2_ERRS+ RBP3_ERRS) / NULLIF(MIN(RBP0_BITS+ RBP1_BITS+ RBP2_BITS+ RBP3_BITS),0) ,10), -- ber_min
      ROUND(MAX(RBP0_ERRS+ RBP1_ERRS+ RBP2_ERRS+ RBP3_ERRS) / NULLIF(MAX(RBP0_BITS+ RBP1_BITS+ RBP2_BITS+ RBP3_BITS),0) ,10), -- ber_max
      ROUND(AVG(rdop),2), -- rdop
      ROUND(SUM(POWER(rdop,2) ),2), -- rdop_s
      ROUND(MIN(rdop),2), -- rdop_min
      ROUND(MAX(rdop),2), -- rdop_max
      ROUND(AVG(rdel90),2), -- rdel90
      ROUND(SUM(POWER(rdel90,2) ),2), -- rdel90_s
      ROUND(MIN(rdel90),2), -- rdel90_min
      ROUND(MAX(rdel90),2), -- rdel90_max
      ROUND(AVG(rdel95),2), -- rdel95
      ROUND(AVG(rdel99),2), -- rdel99
      null AS reslevel
    FROM
    -- select the data where this should be calculated
        SELECT
        FROM
          rfm_meas_hr
        WHERE
          acqtime < fixsecs_down(to_timestamp('07-01-2011 14:00:00,00','dd-mm-yyyy hh24:mi:ss,ff'),600)
          AND (reslevel IS NULL OR reslevel=10)
    -- group the selected data and executes the calculation given by SELECT-statement
    GROUP BY
      -- group the data into 10min packages, indicated by its timestamp
      to_char( EXTRACT(MONTH FROM acqtime)*100000 + EXTRACT(DAY FROM acqtime)*1000 + EXTRACT(HOUR FROM acqtime)*10 + floor(EXTRACT(MINUTE FROM acqtime)/10) ),
      schedule_id,
      box_id
    HAVING
      SUM(nframes)>15
    ;I chould say: I can add indexes if nessecary! At the moment there is one on (acqtime, reslevel) as this improves the access speed. But the query above, executed on typical data already takes 5-7 sec.
    Please let me know if you need any more information.
    Regards!

Maybe you are looking for