Substring in Loop

Hi Friends,
I have the below query.
select
replace(replace(replace(REPLACE(REPLACE(replace(replace(replace(
replace(LPAD(vendor_#, 4, '0') || additional_vendor_#, ' ', '')
, ',', ''), '-', ''), 'LC', ''), '(CIGS)',''),'()',''),'(core)',''),'posonly',''),'(rx)','') AS VEND_NBRS
from XXX_vendors
WHERE VENDOR_# IS NOT NULL;
This query will retrieve VEND_NBRS.
VEND_NBRS
683843474400
002100872504290329933217355935693777597763337291822883509039
600048167094
657373467694
52873621
5272
418404251082141321173574411741974200420242034204420543025216599167258424
12001390255282579353
38810839356469567985
I need to repeatedly extract first 4 bytes (from each record) and insert into another table.
Example : 683843474400
Vendor #: 6838
Vendor#: 4347
vendor#: 4400
Can you please let me know the script ,how to proceed further to insert the data into the table.
I tried using the substring operation and i am getting buffer over flow error.
Thanks,
Divakar

SQL> with t as (
select '683843474400' vend_nbrs from dual union
select '002100872504290329933217355935693777597763337291822883509039' from dual union
select '600048167094' from dual union
select '657373467694' from dual union
select '52873621' from dual union
select '5272' from dual union
select '418404251082141321173574411741974200420242034204420543025216599167258424' from dual union
select '12001390255282579353' from dual union
select '38810839356469567985' from dual
      select level, vend_nbrs, regexp_substr (vend_nbrs, '.{4}', 1, level) single_vn
          from t
connect by          level <= length (vend_nbrs) / 4
                 and prior vend_nbrs = vend_nbrs
                 and prior sys_guid () is not null
     LEVEL VEND_NBRS                                                                        SINGLE_VN
         1 002100872504290329933217355935693777597763337291822883509039                     0021     
         2 002100872504290329933217355935693777597763337291822883509039                     0087     
         3 002100872504290329933217355935693777597763337291822883509039                     2504     
         4 002100872504290329933217355935693777597763337291822883509039                     2903     
         5 002100872504290329933217355935693777597763337291822883509039                     2993     
         6 002100872504290329933217355935693777597763337291822883509039                     3217     
         7 002100872504290329933217355935693777597763337291822883509039                     3559     
         8 002100872504290329933217355935693777597763337291822883509039                     3569     
         9 002100872504290329933217355935693777597763337291822883509039                     3777     
        10 002100872504290329933217355935693777597763337291822883509039                     5977     
        11 002100872504290329933217355935693777597763337291822883509039                     6333     
        12 002100872504290329933217355935693777597763337291822883509039                     7291     
        13 002100872504290329933217355935693777597763337291822883509039                     8228     
        14 002100872504290329933217355935693777597763337291822883509039                     8350     
        15 002100872504290329933217355935693777597763337291822883509039                     9039     
         1 12001390255282579353                                                             1200     
         2 12001390255282579353                                                             1390     
         3 12001390255282579353                                                             2552     
         4 12001390255282579353                                                             8257     
         5 12001390255282579353                                                             9353     
         1 38810839356469567985                                                             3881     
         2 38810839356469567985                                                             0839     
         3 38810839356469567985                                                             3564     
         4 38810839356469567985                                                             6956     
         5 38810839356469567985                                                             7985     
         1 418404251082141321173574411741974200420242034204420543025216599167258424         4184     
         2 418404251082141321173574411741974200420242034204420543025216599167258424         0425     
         3 418404251082141321173574411741974200420242034204420543025216599167258424         1082     
         4 418404251082141321173574411741974200420242034204420543025216599167258424         1413     
         5 418404251082141321173574411741974200420242034204420543025216599167258424         2117     
         6 418404251082141321173574411741974200420242034204420543025216599167258424         3574     
         7 418404251082141321173574411741974200420242034204420543025216599167258424         4117     
         8 418404251082141321173574411741974200420242034204420543025216599167258424         4197     
         9 418404251082141321173574411741974200420242034204420543025216599167258424         4200     
        10 418404251082141321173574411741974200420242034204420543025216599167258424         4202     
        11 418404251082141321173574411741974200420242034204420543025216599167258424         4203     
        12 418404251082141321173574411741974200420242034204420543025216599167258424         4204     
        13 418404251082141321173574411741974200420242034204420543025216599167258424         4205     
        14 418404251082141321173574411741974200420242034204420543025216599167258424         4302     
        15 418404251082141321173574411741974200420242034204420543025216599167258424         5216     
        16 418404251082141321173574411741974200420242034204420543025216599167258424         5991     
        17 418404251082141321173574411741974200420242034204420543025216599167258424         6725     
        18 418404251082141321173574411741974200420242034204420543025216599167258424         8424     
         1 5272                                                                             5272     
         1 52873621                                                                         5287     
         2 52873621                                                                         3621     
         1 600048167094                                                                     6000     
         2 600048167094                                                                     4816     
         3 600048167094                                                                     7094     
         1 657373467694                                                                     6573     
         2 657373467694                                                                     7346     
         3 657373467694                                                                     7694     
         1 683843474400                                                                     6838     
         2 683843474400                                                                     4347     
         3 683843474400                                                                     4400     
55 rows selected.

Similar Messages

  • Regd;- substr function.datatype.

    hi friends,
    how to get a sub string of the column value, for which the data type of column is Long.
    because substr only consider varchar datatype.
    and my string parameter getting more 4000 length. so varchar2 will not be work.
    which datatype suitable for substr to work?

    You can refer to the below code for reference
    SQL> create table lobtest(col_1  number, col_2 clob);
    Table created.
    SQL> ed
    Wrote file afiedt.buf
        declare
            v_data  varchar2(32767);
          begin
          delete lobtest;
            for i in 1..1260 loop
              v_data := v_data||'Testing dbms_lob.substr';
          end loop;
        insert into lobtest values (1,v_data);
        commit;
    end;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> select dbms_lob.substr(col_2,4000,8001) val
    from lobtest
    val
    bstrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting
    dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.s
    ubstrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTestin
    g dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.
    substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesti
    ng dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob
    .substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTest
    ing dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lo
    b.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTes
    ting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_l
    ob.substrTesting dbms_lob.substrTesting dbms_lob.substrTesting dbms_lob.substrTe
    ..............

  • Looping through a string to search for a number?

    I've been trying to use substr to loop through some text in a textfield I have cast as number.  Although there is a problem with this, substr only goes through strings so if I type something as a number, it wont loop through t.  Is there a similar function to loop through numbers?

    use the string methods to find what you're looking for.  you can cast as a number when you've finished using the string methods.
    or, you can use the regular expression class.

  • System.Diagnostics.EventLog - A device attached to the system is not functioning

    I was getting an error ....
    System.ComponentModel.Win32Exception was caught
      ErrorCode=-2147467259
      HResult=-2147467259
      Message=A device attached to the system is not functioning
      NativeErrorCode=31
      Source=System
      StackTrace:
           at System.Diagnostics.EventLogInternal.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName)
           at System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
           at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type)
           at VB_Braums_ClassLib.LogIt.WriteEventLog(String Entry, EventLogEntryType eventType, String Source) in \\Corp01\Vol1\Mis\Pccode\Ms.net\ProductionLibs\ProductionLibs\ProdLibCommon.vb:line 3666
      InnerException: 
    This code is in a library, so I create a "hello world" to demonstrate the issue. I will post it at the end. This .net 4 framework and it's been around for a while in our code. We are starting to upgrade from XP to Win 7. Basically event log sizes
    are limited to the 32667 number. So we had a test, if the string is bigger than that, then we would write it in 32000 byte chucks. On two different win7 boxes we get the "device attached" error message. Run the same code on a XP box and it works.
    Oh, and the Win 7 boxes are 64 bit.  I wonder if the win 7 32 bit would have the same issue? Can others duplicate it? The tmpsize seems to be different numbers, but if you play with it, you can get it down to number x works and (x+1) does not.
    Here the code .....
    Module Module1
        Sub Main()
            Dim logName As String = "BraumsLog"
            Dim objEventLog As New System.Diagnostics.EventLog()
            Dim needCreate As Boolean = False
            Dim Source As String = ""
            If Source.Length = 0 Then Source = "Test"
            Dim Entry As String = "".PadLeft(64000, "1"c)
            'Register the App as an Event Source
            If EventLog.SourceExists(Source) Then
                Dim slog As String = EventLog.LogNameFromSourceName(Source, ".")
                If slog <> logName Then EventLog.DeleteEventSource(Source) : needCreate = True
            Else
                needCreate = True
            End If
            If needCreate Then EventLog.CreateEventSource(Source, logName)
            objEventLog.Source = Source
            '*********** New Code ****************
            objEventLog.MaximumKilobytes = 20480
            objEventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0)
            'WriteEntry is overloaded; this is one
            'of 10 ways to call it
            Dim tmp As String = ""
            Dim tmpSize As Integer = 32000 '31890 works 31891 does not
            Do While Entry.Length > tmpSize
                tmp = Entry.Substring(0, tmpSize - 1)
                objEventLog.WriteEntry(tmp, EventLogEntryType.Information)
                Debug.WriteLine(tmp.Length.ToString)
                Entry = Entry.Substring(tmpSize)
            Loop
            tmp = Entry
            objEventLog.WriteEntry(tmp, EventLogEntryType.Information)
        End Sub
    End Module

    Run the same code on an XP 64 bit box and it works? XP comes in multiple flavors.
    Perhaps you should compile to x86 CPU and see if it works on Win 7 64 bit. Win 7 comes in 32 and 64 bit also.
    On the other hand Win 7 service pack 1 mainstream support ended on the 13th of this month. Extended support ends in 2020 supposedly. Perhaps you should upgrade to Win 8.1 instead. Win 10 is coming soon enough.
    Windows lifecycle fact sheet
    Microsoft Product Lifecycle Search - Windows 7 result
    La vida loca

  • How to find certain words based on table without overwriting the old one

    Hello,
     I have a list of words available in one particular table, based on those records i need to match it up with one specific column on another table. Based on that match i need to update the same. below is answer for this question;
    Design a new query. Select your data table and your words table. No join line between them.
    Drag datatable.* to the design grid, and the field to check. In the criteria for that field write:
    Like '*' & [wordstable]![wordsfield] & "*"
    (of course you change this to your object names)
    But now my another question is that how i can do update without replacing the existing one. Like for example " Peter is engineering degree".
    In this example if i have words like ring and degree on my reference table, then as per the solution it will update the degree first then later if its find ring on the text then it will overwrite the degree on the particular column. How i can prevent
    this?
    VinWin06

    But now my another question is that how i can do update without replacing the existing one. Like for example " Peter is engineering degree".
    I think what you are saying is that you want to avoid specious substring matches such as finding 'engineering' when searching for 'ring'.  Right?  If so use the following function rather than the LIKE operator to identify the 'word' rather than merely
    a substring:
    Public Function FindWord(varFindIn As Variant, varWord As Variant) As Boolean
       Const PUNCLIST = """' .,?!:;(){}[]/"
       Dim intPos As Integer
       FindWord = False
       If Not IsNull(varFindIn) And Not IsNull(varWord) Then
           intPos = InStr(varFindIn, varWord)
           ' loop until no instances of sought substring found
           Do While intPos > 0
               ' is it at start of string
               If intPos = 1 Then
                   ' is it whole string?
                   If Len(varFindIn) = Len(varWord) Then
                       FindWord = True
                       Exit Function
                   ' is it followed by a space or punctuation mark?
                   ElseIf InStr(PUNCLIST, Mid(varFindIn, intPos + Len(varWord), 1)) > 0 Then
                       FindWord = True
                       Exit Function
                   End If
               Else
                   ' is it precedeed by a space or punctuation mark?
                   If InStr(PUNCLIST, Mid(varFindIn, intPos - 1, 1)) > 0 Then
                       ' is it at end of string or followed by a space or punctuation mark?
                       If InStr(PUNCLIST, Mid(varFindIn, intPos + Len(varWord), 1)) > 0 Then
                           FindWord = True
                           Exit Function
                       End If
                   End If
               End If
               ' remove characters up to end of first instance
               ' of sought substring before looping
               varFindIn = Mid(varFindIn, intPos + 1)
               intPos = InStr(varFindIn, varWord)
           Loop
       End If
    End Function
    You can supplement this with the following functions to find any or all of multiple words in the same string expression:
    Public Function FindAnyWord(varFindIn, ParamArray varWordList() As Variant) As Boolean
        Dim var As Variant
        For Each var In varWordList
            If FindWord(varFindIn, var) Then
                FindAnyWord = True
                Exit Function
            End If
        Next var
    End Function
    Public Function FindAllWords(varFindIn, ParamArray varWordList() As Variant) As Boolean
        Dim var As Variant
        For Each var In varWordList
            If Not FindWord(varFindIn, var) Then
                FindAllWords = False
                Exit Function
            Else
                FindAllWords = True
            End If
        Next var
    End Function
    You can edit the PUNCLIST constant in the first function to allow for any other terminating or leading punctuation characters which may exist, in non-English text for instance.
    Ken Sheridan, Stafford, England

  • How to Split the string using Substr and instr using loop condition

    Hi every body,
    I have below requirement.
    I need to split the string and append with single quotes('') followed by , (comma) and reassign entire values into another variable. so that i can use it where clause of update statement
    for example I am reciveing value as follows
    ALN varchar2(2000):=(12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434);
    Note: In the above variable i see 8 transactions, where as in real scenario i donot how many transaction i may recive.
    after modification i need above transactions should in below format
    ALTR Varchar2(2000):=('12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434');
    kindly help how to use substr and instr in normal loop or for loop or while loop while modifying the above transactions.
    Please help me to sort out this issue.
    Many Thanks.
    Edited by: user627525 on Dec 15, 2011 11:49 AM

    Try this - may not be the best way but...:
    create or replace type myTableType as table of varchar2(255)
    declare
    v_array mytabletype;
    v_new_str varchar2(4000);
    function str2tbl
             (p_str   in varchar2,
              p_delim in varchar2 default '.')
             return      myTableType
        as
            l_str        long default p_str || p_delim;
             l_n        number;
             l_data     myTableType := myTabletype();
        begin
            loop
                l_n := instr( l_str, p_delim );
                exit when (nvl(l_n,0) = 0);
                l_data.extend;
                l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
                l_str := substr( l_str, l_n+length(p_delim) );
            end loop;
            return l_data;
       end;
    begin
      v_array := str2tbl ('12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434', ',');
          FOR i IN 1 .. v_array.COUNT LOOP
             v_new_str := v_new_str || ''''||v_array(i)||'''' || ',';
          END LOOP;
       dbms_output.put_line(RTRIM(v_new_str, ','));
    end;  
    OUTPUT:
    =======
    '12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434'HTH
    Edited by: user130038 on Dec 15, 2011 12:11 PM

  • Problem Sending mails in a loop using JavaMail API

    Hello All,
    I am sending emails in a loop(one after the other) using JavaMail API,but the problem is, if the first two,three email addresses in the loop are Valid it sends the Email Properly, but if the Fourth or so is Invalid Address it throws an Exception....
    "javax.mail.SendFailedException: Sending failed;"
    nested exception is:
    javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    javax.mail.SendFailedException: 450 <[email protected]>:Recipient address rejected: Domain not found......
    So if i want to send hundereds of emails and if one of the Emails inbetween is Invalid the process Stops at that point and i could not send the other emails in the Loop......
    How Could i Trap the exception thrown and handle it in such a way, so that the loops continues ..
    Is there something with the SMTP Server....?
    The code which i am using is as follows....
    <Code>...
    try {
    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(JNDINames.MAIL_SESSION);
    if (Debug.debuggingOn)
    session.setDebug(true);
    // construct the message
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(eMess.getEmailSender()));
    String to = "";
    msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(to, false));
    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(eMess.getEmailReceiver(), false));
    msg.setSubject(eMess.getSubject());
    msg.setContent(eMess.getHtmlContents(),"text/plain");
    msg.saveChanges();                
    Transport.send(msg);
    } catch (Exception e) {
    Debug.print("createAndSendMail exception : " + e);
    throw new MailerAppException("Failure while sending mail");
    </Code>....
    Please give me any suggestions regarding it....and guide me accordingly..
    Thanks a million in advance...
    Regards
    Sam

    How about something like the code attached here. Be aware it is lifted and edited out of an app we have here so it may require changing to get it to work. If it don't work - don't come asking for help as this is only a rough example of one way of doing it. RTFM - that's how we worked it out!
    SH
    try {
    Transport.send(msg);
    // If we get to here then the mail went OK so update all the records in the email as sent
    System.out.println("Email sent OK");
    catch (MessagingException mex) {
    System.out.println("Message error");
    Exception ex = mex;
    do {
    if (ex instanceof SendFailedException) {
    if (ex.getMessage().startsWith("Sending failed")) {
    // Ignore this message as we want to know the real reason for failure
    // If we get an Invalid Address error or a Message partially delivered message process the message
    if (ex.getMessage().startsWith("Message partially delivered")
    || ex.getMessage().startsWith("Invalid Addresses")) {
    // This message is of interest as we need to process the actual individual addresses
    System.out.println(ex.getMessage().substring(0, ex.getMessage().indexOf(";")));
    // Now get the addresses from the SendFailedException
    SendFailedException sfex = (SendFailedException) ex;
    Address[] invalid = sfex.getInvalidAddresses();
    if (invalid != null) {
    System.out.println("Invalid Addresse(s) found -");
    if (invalid.length > 0) {
    for (int x = 0; x < invalid.length; x++) {
    System.out.println(invalid[x].toString().trim());
    Address[] validUnsent = sfex.getValidUnsentAddresses();
    if (validUnsent != null) {
    System.out.println("Valid Unsent Addresses found -");
    if (validUnsent.length > 0) {
    for (int x = 0; x < validUnsent.length; x++) {
    System.out.println(validUnsent[x].toString().trim());
    Address[] validSent = sfex.getValidSentAddresses();
    if (validSent != null) {
    System.out.println("Valid Sent Addresses found -");
    if (validSent.length > 0) {
    for (int x = 0; x < validSent.length; x++) {
    System.out.println(validSent[x].toString().trim());
    if (ex instanceof MessagingException)
    ex = ((MessagingException) ex).getNextException();
    else {
    // This is a general catch all and we should assume that no messages went and should stop
    System.out.println(ex.toString());
    throw ex;
    } while (ex != null);

  • Need to Loop if No Data Found

    Hi,
    I have been tasked with writing an Oracle Function to query a set of tables to locate data that best matches what a user needs.
    If data is not returned in a given query, we need the procedure to loop and run a modified query. If that query does not give data, we continue to loop and refine until we reach a point where we have expended all of our filtering levels.
    I am new to writing PL SQL and have been doing a lot of googling trying to figure out how to do this, but I am stuck :(
    I have not been able to figure out how to continue looping in the Procedure when there are no results in the record set.
    It is probably something simple, I just haven't been able to figure it out.
    HERE'S WHAT SEEMS TO BE THE PERTINENT PART OF THE CODE:
    OPEN v_cursor FOR v_sql;
    DBMS_OUTPUT.PUT_LINE(v_sql);
    --THIS IS THE PORTION I AM HAVING PROBLEMS WITH:
    --If there are results I want to set the following
    --haveResultsOrAllQueriesDone := TRUE;
    --Otherwise, I want to leave haveResultsOrAllQueriesDone := FALSE; and continue to loop
    RETURN v_cursor;
    END LOOP;
    Thanks in advance for any direction any one can give me.
    Thanks!
    :) Anne
    PS:
    HERE IS THE COMPLETE FUNCTION AS I HAVE IT SO FAR:
    create or replace
    FUNCTION LOCATEACONSULTANT_function
    p_action IN VARCHAR2,
    p_first_name IN VARCHAR2,
    p_last_name IN VARCHAR2,
    p_exact_match IN VARCHAR2,
    p_country_code IN VARCHAR2,
    p_state IN VARCHAR2,
    p_city IN VARCHAR2,
    p_zip_or_postalcode IN VARCHAR2,
    p_language_code IN VARCHAR2)
    RETURN types.ref_cursor
    AS
    v_cursor types.ref_cursor;
    v_temp_cursor types.ref_cursor;
    BEGIN
    DBMS_OUTPUT.ENABLE(1000000);
    DECLARE
    type ref_cursor
    IS
    REF
    CURSOR;
    cursor_locateAConsultant ref_cursor;
    v_select VARCHAR2(3000);
    v_from VARCHAR2(2000);
    v_where VARCHAR2(4000);
    v_sql VARCHAR2(4000);
    stateMapped ref_zip_mappings.state%type;
    countyMapped ref_zip_mappings.county%type;
    cityMapped ref_zip_mappings.city%type;
    haveQueriedLanguage BOOLEAN := FALSE;
    haveQueriedZip BOOLEAN := FALSE;
    haveQueriedCity BOOLEAN := FALSE;
    haveQueriedCounty BOOLEAN := FALSE;
    haveQueriedState BOOLEAN := FALSE;
    haveResultsOrAllQueriesDone BOOLEAN := FALSE;
    haveDoneAllQueries BOOLEAN := FALSE;
    tempLikeZip VARCHAR2(100);
    BEGIN
    v_select := 'SELECT customers.customer_id, customers.last_name, customers.first_name, ';
    v_select := v_select || ' customer_contacts.email_address, addresses.state, addresses.city, ';
    v_select := v_select || ' customer_contacts.web_site, customer_languages.language_code, customer_titles.pqv ';
    v_from := ' FROM customers, customer_addresses, addresses, customer_contacts, customer_titles, customer_languages';
    v_where := ' WHERE customers.customer_id = customer_addresses.customer_id ';
    v_where := v_where || ' AND customer_addresses.address_id = addresses.address_id ';
    v_where := v_where || ' AND customers.customer_id = customer_contacts.customer_id ';
    v_where := v_where || ' AND customers.customer_id = customer_titles.customer_id ';
    v_where := v_where || ' AND customers.preferred_language_code = customer_languages.language_code ';
    v_where := v_where || ' AND UPPER(addresses.country_code) = UPPER(''' || p_country_code || ''') ';
    v_where := v_where || ' AND UPPER(customers.exclude_locate) = '||''''||'N'||''''||'';
    v_where := v_where || ' AND UPPER(customer_titles.customer_type) = '||''''||'CON'||''''||'';
    v_where := v_where || ' AND UPPER(customer_titles.dp_id) LIKE '||''''||'CN%'||''''||'';
    -- Line below assumes that 1 is the billing_address_type
    v_where := v_where || ' AND customer_addresses.address_type_code = 1 ';
    v_where := v_where || ' AND ';
    v_where := v_where || ' ( ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MYARBONNE.COM%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MYARBONNE.COM.AU%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MYARBONNE.CA%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MYARBONNE.UK%'||''''||' ';
    v_where := v_where || ' ) ';
    IF (UPPER(p_action) =UPPER('search')) THEN
    v_where := v_where || ' AND UPPER(addresses.state) = UPPER(trim(''' || p_state || ''')) ';
    IF UPPER(p_exact_match) = UPPER('y') THEN
    v_where := v_where || ' AND UPPER(customers.first_name) = UPPER(trim(''' || p_first_name || ''')) ';
    ELSE
    v_where := v_where || ' AND UPPER(SOUNDEX(customers.first_name)) = UPPER(SOUNDEX(trim(''' || p_first_name || '''))) ';
    END IF;
    IF UPPER(p_last_name) <> '' THEN
    IF UPPER(p_exact_match) = UPPER('y') THEN
    v_where := v_where || ' AND UPPER(customers.last_name) = UPPER(trim(''' || p_last_name || ''')) ';
    ELSE
    v_where := v_where || ' AND UPPER(SOUNDEX(customers.last_name)) = UPPER(SOUNDEX(trim(''' || p_last_name || ''')) ';
    END IF;
    END IF;
    IF UPPER(p_city) <> '' THEN
    v_where := v_where || ' AND UPPER(addresses.city) = UPPER(''' || p_city || ''') ';
    END IF;
    IF UPPER(p_zip_or_postalcode) <> '' THEN
    v_where := v_where || ' AND UPPER(addresses.zip_or_postalcode) = UPPER(''' || p_zip_or_postalcode || ''') ';
    END IF;
    END IF;
    WHILE (haveResultsOrAllQueriesDone = FALSE)
    LOOP
    IF (p_action = 'locate') THEN
    IF (haveQueriedLanguage = FALSE) THEN
    IF (p_language_code <> '') THEN
    v_where := v_where|| ' AND UPPER(customer_languages.language_code) = UPPER(''' || p_language_code || ''') ';
    haveQueriedLanguage := TRUE;
    END IF;
    --ELSE
    -- haveQueriedLanguage := FALSE;
    END IF;
    IF (haveQueriedZip = FALSE) THEN
    v_where := v_where|| ' AND UPPER(addresses.zip_or_postalcode) = UPPER(''' || p_zip_or_postalcode || ''') ';
    IF (haveQueriedLanguage = FALSE) THEN
    haveQueriedZip := TRUE;
    END IF;
    ELSIF (haveQueriedCity = FALSE) THEN
    IF (p_city <> '') THEN
    v_where := v_where|| ' AND UPPER(addresses.city) = UPPER('||''''|| p_city ||''''||') ' ;
    ELSE
    IF (p_country_code = 'UK') THEN
    tempLikeZip := SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 2 ));
    v_where := v_where || ' AND UPPER(addresses.zip_or_postalcode) LIKE UPPER(TRIM('||'''%'||tempLikeZip ||''''||')) ' ;
    ELSE
    OPEN cursor_locateAConsultant FOR 'SELECT city FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER(TRIM('||''''|| p_zip_or_postalcode ||''''||')) ' ;
    -- OPEN v_temp_cursor FOR 'SELECT city FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER(TRIM('||''''|| p_zip_or_postalcode ||''''||')) ' ;
    LOOP
    FETCH cursor_locateAConsultant INTO cityMapped;
    EXIT
    WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    -- RETURN v_temp_cursor;
    v_where := v_where || ' AND UPPER(addresses.city) = UPPER('||''''|| cityMapped ||''''||') ' ;
    END IF;
    END IF;
    haveQueriedCity := TRUE;
    ELSIF haveQueriedCounty = FALSE THEN
    IF (p_country_code = 'UK') THEN
    tempLikeZip := UPPER(SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 3 )));
    v_where := v_where|| ' AND UPPER(addresses.zip_or_postalcode) LIKE '||'''%'||tempLikeZip ||''''||' ' ;
    ELSE
    OPEN cursor_locateAConsultant FOR 'SELECT county FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER('||''''|| p_zip_or_postalcode ||''''||') ' ;
    LOOP
    FETCH cursor_locateAConsultant INTO countyMapped;
    EXIT
    WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    v_where := v_where|| ' AND UPPER(addresses.county) = UPPER('||''''|| countyMapped ||''''||') ' ;
    END IF;
    haveQueriedCounty := TRUE;
    END IF;
    ELSIF haveQueriedState = FALSE THEN
    IF (p_state <> '') THEN
    v_where := v_where|| ' AND UPPER(addresses.state) = UPPER('||''''|| p_state ||''''||') ' ;
    ELSE
    IF (p_country_code = 'UK') THEN
    tempLikeZip := UPPER(SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 4 )));
    v_where := v_where|| ' AND UPPER(addresses.zip_or_postalcode) LIKE '||'''%'||tempLikeZip ||''''||' ' ;
    ELSE
    OPEN cursor_locateAConsultant FOR 'SELECT state FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER('||''''|| p_zip_or_postalcode ||''''||') ' ;
    LOOP
    FETCH cursor_locateAConsultant INTO stateMapped;
    EXIT WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    v_where := v_where|| ' AND UPPER(addresses.state) = UPPER('||''''|| stateMapped ||''''||') ' ;
    END IF;
    haveQueriedState := TRUE;
    END IF;
    END IF;
    v_sql := v_select || v_from || v_where;
    OPEN v_cursor FOR v_sql;
    DBMS_OUTPUT.PUT_LINE(v_sql);
    --THIS IS THE PORTION I AM HAVING PROBLEMS WITH:
    --If there are results I want to set the following
    --haveResultsOrAllQueriesDone := TRUE;
    --Otherwise, I want to leave haveResultsOrAllQueriesDone := FALSE; and continue to loop
    RETURN v_cursor;
    END LOOP;
    END;
    END;

    Thank you so very much for your kindness in answering my question.
    Your suggestion helped.
    We will be accessing this Procedure from a Java Class... I'm not sure how... but I know it is possible and probably not hard... If any one has suggestions, that would be helpful, but I am not concerned about that right now, as I think it should be straight forward... Hopefully I'm right :)
    Thank you again!
    Anne
    Here's the code... which works, though may still need some more fine tuning:
    create or replace
    FUNCTION LOCATEACONSULTANT_function
    p_action IN VARCHAR2,
    p_first_name IN VARCHAR2,
    p_last_name IN VARCHAR2,
    p_exact_match IN VARCHAR2,
    p_country_code IN VARCHAR2,
    p_state IN VARCHAR2,
    p_city IN VARCHAR2,
    p_zip_or_postalcode IN VARCHAR2,
    p_language_code IN VARCHAR2)
    RETURN types.ref_cursor
    AS
    v_cursor types.ref_cursor;
    BEGIN
    DBMS_OUTPUT.ENABLE(1000000);
    DECLARE
    type ref_cursor
    IS
    REF
    CURSOR;
    cursor_locateAConsultant types.ref_cursor;
    v_select VARCHAR2(3000);
    v_from VARCHAR2(2000);
    v_where VARCHAR2(4000);
    v_where_filter VARCHAR2(4000);
    v_sql VARCHAR2(4000);
    v_select1 VARCHAR2(4000):= 'SELECT 1 ';
    v_temp VARCHAR2(1000);
    stateMapped ref_zip_mappings.state%type;
    countyMapped ref_zip_mappings.county%type;
    cityMapped ref_zip_mappings.city%type;
    v_hasRecords NUMBER := 0;
    haveQueriedLanguage BOOLEAN := FALSE;
    haveQueriedZip BOOLEAN := FALSE;
    haveQueriedCity BOOLEAN := FALSE;
    haveQueriedCounty BOOLEAN := FALSE;
    haveQueriedState BOOLEAN := FALSE;
    haveResultsOrAllQueriesDone BOOLEAN := FALSE;
    haveDoneAllQueries BOOLEAN := FALSE;
    tempLikeZip VARCHAR2(100);
    BEGIN
    v_select := 'SELECT customers.customer_id, customers.first_name, customers.last_name, ';
    v_select := v_select || ' addresses.country_code, addresses.state, addresses.city, ';
    v_select := v_select || ' addresses.zip_or_postalcode, customer_contacts.email_address, ';
    v_select := v_select || ' customer_contacts.web_site, customer_languages.language_code';
    v_from := ' FROM customers, customer_addresses, addresses, customer_contacts, customer_titles, customer_languages';
    v_where := ' WHERE customers.customer_id = customer_addresses.customer_id ';
    v_where := v_where || ' AND customer_addresses.address_id = addresses.address_id ';
    v_where := v_where || ' AND customers.customer_id = customer_contacts.customer_id ';
    v_where := v_where || ' AND customers.customer_id = customer_titles.customer_id ';
    v_where := v_where || ' AND customers.preferred_language_code = customer_languages.language_code ';
    v_where := v_where || ' AND UPPER(addresses.country_code) = UPPER(''' || p_country_code || ''') ';
    v_where := v_where || ' AND UPPER(customers.exclude_locate) = '||''''||'N'||''''||'';
    v_where := v_where || ' AND UPPER(customer_titles.customer_type) = '||''''||'CON'||''''||'';
    v_where := v_where || ' AND UPPER(customer_titles.dp_id) LIKE '||''''||'CN%'||''''||'';
    -- Line below assumes that 1 is the billing_address_type
    v_where := v_where || ' AND customer_addresses.address_type_code = 1 ';
    v_where := v_where || ' AND ';
    v_where := v_where || ' ( ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MY%.COM%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MY%.COM.AU%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MY%.CA%'||''''||' ';
    v_where := v_where || ' OR ';
    v_where := v_where || ' UPPER(customer_contacts.web_site) LIKE '||''''||'%MY%.UK%'||''''||' ';
    v_where := v_where || ' ) ';
    WHILE (haveResultsOrAllQueriesDone = FALSE)
    LOOP
    CASE
    WHEN (UPPER(p_action) =UPPER('search')) THEN
    v_where_filter := '';
    v_where_filter := v_where_filter || ' AND UPPER(addresses.state) = UPPER(trim(''' || p_state || ''')) ';
    IF UPPER(p_exact_match) = UPPER('y') THEN
    v_where_filter := v_where_filter || ' AND UPPER(customers.first_name) = UPPER(trim(''' || p_first_name || ''')) ';
    ELSE
    v_where_filter := v_where_filter || ' AND UPPER(SOUNDEX(customers.first_name)) = UPPER(SOUNDEX(trim(''' || p_first_name || '''))) ';
    END IF;
    IF UPPER(p_last_name) <> '' THEN
    IF UPPER(p_exact_match) = UPPER('y') THEN
    v_where_filter := v_where_filter || ' AND UPPER(customers.last_name) = UPPER(trim(''' || p_last_name || ''')) ';
    ELSE
    v_where_filter := v_where_filter || ' AND UPPER(SOUNDEX(customers.last_name)) = UPPER(SOUNDEX(trim(''' || p_last_name || ''')) ';
    END IF;
    END IF;
    IF UPPER(p_city) <> '' THEN
    v_where_filter := v_where_filter || ' AND UPPER(addresses.city) = UPPER(''' || p_city || ''') ';
    END IF;
    IF UPPER(p_zip_or_postalcode) <> '' THEN
    v_where_filter := v_where_filter || ' AND UPPER(addresses.zip_or_postalcode) = UPPER(''' || p_zip_or_postalcode || ''') ';
    END IF;
    WHEN (p_action = 'locate') THEN
    v_where_filter := '';
    IF (haveQueriedLanguage = FALSE) THEN
    IF (p_language_code <> '') THEN
    v_where_filter := v_where_filter|| ' AND UPPER(customer_languages.language_code) = UPPER(''' || p_language_code || ''') ';
    haveQueriedLanguage := TRUE;
    END IF;
    --ELSE
    -- haveQueriedLanguage := FALSE;
    END IF;
    CASE
    WHEN (haveQueriedZip = FALSE) THEN
    v_where_filter := v_where_filter || ' AND UPPER(addresses.zip_or_postalcode) = UPPER(''' || p_zip_or_postalcode || ''') ';
    IF (haveQueriedLanguage = FALSE) THEN
    haveQueriedZip := TRUE;
    END IF;
    WHEN (haveQueriedCity = FALSE) THEN
    IF (p_city <> '') THEN
    v_where_filter := v_where_filter || ' AND UPPER(addresses.city) = UPPER('||''''|| p_city ||''''||') ' ;
    ELSE
    IF (p_country_code = 'UK') THEN
    tempLikeZip := SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 2 ));
    v_where_filter := v_where_filter || ' AND UPPER(addresses.zip_or_postalcode) LIKE UPPER(TRIM('||'''%'||tempLikeZip ||''''||')) ' ;
    ELSE
    v_temp := 'SELECT city FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER(TRIM('||''''|| p_zip_or_postalcode ||''''||')) ';
    OPEN cursor_locateAConsultant FOR v_temp ;
    LOOP
    FETCH cursor_locateAConsultant INTO cityMapped;
    EXIT
    WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    cityMapped := TRIM(cityMapped);
    v_where_filter := v_where_filter || ' AND UPPER(addresses.city) = UPPER('||''''|| cityMapped ||''''||') ' ;
    END IF;
    END IF;
    haveQueriedCity := TRUE;
    WHEN (haveQueriedCounty = FALSE) THEN
    IF (p_country_code = 'UK') THEN
    tempLikeZip := UPPER(SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 3 )));
    v_where_filter := v_where_filter || ' AND UPPER(addresses.zip_or_postalcode) LIKE '||'''%'||tempLikeZip ||''''||' ' ;
    ELSE
    OPEN cursor_locateAConsultant FOR 'SELECT county FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER('||''''|| p_zip_or_postalcode ||''''||') ' ;
    LOOP
    FETCH cursor_locateAConsultant INTO countyMapped;
    EXIT
    WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    countyMapped := TRIM(countyMapped);
    v_where_filter := v_where_filter || ' AND UPPER(addresses.province_county) = UPPER(TRIM('||''''|| countyMapped ||''''||')) ' ;
    END IF;
    haveQueriedCounty := TRUE;
    WHEN (haveQueriedState = FALSE) THEN
    IF (p_state <> '') THEN
    v_where_filter := v_where_filter || ' AND UPPER(addresses.state) = UPPER('||''''|| p_state ||''''||') ' ;
    ELSE
    IF (p_country_code = 'UK') THEN
    tempLikeZip := UPPER(SUBSTR(p_zip_or_postalcode,( LENGTH(TRIM(p_zip_or_postalcode)) - 4 )));
    v_where_filter := v_where_filter || ' AND UPPER(addresses.zip_or_postalcode) LIKE '||'''%'||tempLikeZip ||''''||' ' ;
    ELSE
    OPEN cursor_locateAConsultant FOR 'SELECT state FROM ref_zip_mappings where UPPER(zip_or_postalcode) = UPPER('||''''|| p_zip_or_postalcode ||''''||') ' ;
    LOOP
    FETCH cursor_locateAConsultant INTO stateMapped;
    EXIT
    WHEN cursor_locateAConsultant%NOTFOUND;
    END LOOP;
    CLOSE cursor_locateAConsultant;
    stateMapped := TRIM(stateMapped);
    v_where_filter := v_where_filter || ' AND UPPER(addresses.state) = UPPER(TRIM('||''''|| stateMapped ||''''||')) ' ;
    END IF;
    haveQueriedState := TRUE;
    END IF;
    END CASE;
    END CASE;
    v_select1 := 'SELECT 1 ' || v_from || v_where || v_where_filter;
    OPEN v_cursor FOR v_select1;
    DBMS_OUTPUT.PUT_LINE(v_select1);
    FETCH v_cursor INTO v_hasRecords;
    IF (v_hasRecords = 1) THEN
    haveResultsOrAllQueriesDone := TRUE;
    ELSE
    haveResultsOrAllQueriesDone := FALSE;
    END IF;
    IF ((haveResultsOrAllQueriesDone = TRUE) OR (haveQueriedState = TRUE)) THEN
    v_sql := v_select || v_from || v_where || v_where_filter;
    OPEN v_cursor FOR v_sql;
    DBMS_OUTPUT.PUT_LINE(v_sql);
    RETURN v_cursor;
    END IF;
    END LOOP;
    END;
    END;

  • Need to increase performance-bulk collect in cursor with limit and in the for loop inserting into the trigger table

    Hi all,
    I have a performance issue in the below code,where i am trying to insert the data from table_stg into target_tab and in parent_tab tables and then to child tables via cursor with bulk collect .the target_tab and parent_tab are huge tables and have a row wise trigger enabled on it .the trigger is mandatory . This timetaken for this block to execute is 5000 seconds.Now my requirement is to reduce it to 5 to 10 mins.
    can someone please guide me here.Its bit urgent .Awaiting for your response.
    declare
    vmax_Value NUMBER(5);
      vcnt number(10);
      id_val number(20);
      pc_id number(15);
      vtable_nm VARCHAR2(100);
      vstep_no  VARCHAR2(10);
      vsql_code VARCHAR2(10);
      vsql_errm varchar2(200);
      vtarget_starttime timestamp;
      limit_in number :=10000;
      idx           number(10);
              cursor stg_cursor is
             select
                   DESCRIPTION,
                   SORT_CODE,
                   ACCOUNT_NUMBER,
                     to_number(to_char(CORRESPONDENCE_DATE,'DD')) crr_day,
                     to_char(CORRESPONDENCE_DATE,'MONTH') crr_month,
                     to_number(substr(to_char(CORRESPONDENCE_DATE,'DD-MON-YYYY'),8,4)) crr_year,
                   PARTY_ID,
                   GUID,
                   PAPERLESS_REF_IND,
                   PRODUCT_TYPE,
                   PRODUCT_BRAND,
                   PRODUCT_HELD_ID,
                   NOTIFICATION_PREF,
                   UNREAD_CORRES_PERIOD,
                   EMAIL_ID,
                   MOBILE_NUMBER,
                   TITLE,
                   SURNAME,
                   POSTCODE,
                   EVENT_TYPE,
                   PRIORITY_IND,
                   SUBJECT,
                   EXT_PRD_ID_TX,
                   EXT_PRD_HLD_ID_TX,
                   EXT_SYS_ID,
                   EXT_PTY_ID_TX,
                   ACCOUNT_TYPE_CD,
                   COM_PFR_TYP_TX,
                   COM_PFR_OPT_TX,
                   COM_PFR_RSN_CD
             from  table_stg;
    type rec_type is table of stg_rec_type index by pls_integer;
    v_rt_all_cols rec_type;
    BEGIN
      vstep_no   := '0';
      vmax_value := 0;
      vtarget_starttime := systimestamp;
      id_val    := 0;
      pc_id     := 0;
      success_flag := 0;
              vstep_no  := '1';
              vtable_nm := 'before cursor';
        OPEN stg_cursor;
              vstep_no  := '2';
              vtable_nm := 'After cursor';
       LOOP
              vstep_no  := '3';
              vtable_nm := 'before fetch';
    --loop
        FETCH stg_cursor BULK COLLECT INTO v_rt_all_cols LIMIT limit_in;
                  vstep_no  := '4';
                  vtable_nm := 'after fetch';
    --EXIT WHEN v_rt_all_cols.COUNT = 0;
        EXIT WHEN stg_cursor%NOTFOUND;
    FOR i IN 1 .. v_rt_all_cols.COUNT
      LOOP
       dbms_output.put_line(upper(v_rt_all_cols(i).event_type));
        if (upper(v_rt_all_cols(i).event_type) = upper('System_enforced')) then
                  vstep_no  := '4.1';
                  vtable_nm := 'before seq sel';
              select PC_SEQ.nextval into pc_id from dual;
                  vstep_no  := '4.2';
                  vtable_nm := 'before insert corres';
              INSERT INTO target1_tab
                           (ID,
                            PARTY_ID,
                            PRODUCT_BRAND,
                            SORT_CODE,
                            ACCOUNT_NUMBER,
                            EXT_PRD_ID_TX,         
                            EXT_PRD_HLD_ID_TX,
                            EXT_SYS_ID,
                            EXT_PTY_ID_TX,
                            ACCOUNT_TYPE_CD,
                            COM_PFR_TYP_TX,
                            COM_PFR_OPT_TX,
                            COM_PFR_RSN_CD,
                            status)
             VALUES
                            (pc_id,
                             v_rt_all_cols(i).party_id,
                             decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
                             v_rt_all_cols(i).sort_code,
                             'XXXX'||substr(trim(v_rt_all_cols(i).ACCOUNT_NUMBER),length(trim(v_rt_all_cols(i).ACCOUNT_NUMBER))-3,4),
                             v_rt_all_cols(i).EXT_PRD_ID_TX,
                             v_rt_all_cols(i).EXT_PRD_HLD_ID_TX,
                             v_rt_all_cols(i).EXT_SYS_ID,
                             v_rt_all_cols(i).EXT_PTY_ID_TX,
                             v_rt_all_cols(i).ACCOUNT_TYPE_CD,
                             v_rt_all_cols(i).COM_PFR_TYP_TX,
                             v_rt_all_cols(i).COM_PFR_OPT_TX,
                             v_rt_all_cols(i).COM_PFR_RSN_CD,
                             NULL);
                  vstep_no  := '4.3';
                  vtable_nm := 'after insert corres';
        else
              select COM_SEQ.nextval into id_val from dual;
                  vstep_no  := '6';
                  vtable_nm := 'before insertcomm';
          if (upper(v_rt_all_cols(i).event_type) = upper('REMINDER')) then
                vstep_no  := '6.01';
                  vtable_nm := 'after if insertcomm';
              insert into parent_tab
                 (ID ,
                 CTEM_CODE,
                 CHA_CODE,            
                 CT_CODE,                           
                 CONTACT_POINT_ID,             
                 SOURCE,
                 RECEIVED_DATE,                             
                 SEND_DATE,
                 RETRY_COUNT)
              values
                 (id_val,
                  lower(v_rt_all_cols(i).event_type), 
                  decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
                  'Email',
                  v_rt_all_cols(i).email_id,
                  'IADAREMINDER',
                  systimestamp,
                  systimestamp,
                  0);  
         else
                vstep_no  := '6.02';
                  vtable_nm := 'after else insertcomm';
              insert into parent_tab
                 (ID ,
                 CTEM_CODE,
                 CHA_CODE,            
                 CT_CODE,                           
                 CONTACT_POINT_ID,             
                 SOURCE,
                 RECEIVED_DATE,                             
                 SEND_DATE,
                 RETRY_COUNT)
              values
                 (id_val,
                  lower(v_rt_all_cols(i).event_type), 
                  decode(v_rt_all_cols(i).product_brand,'LTB',2,'HLX',1,'HAL',1,'BOS',3,'VER',4,0),
                  'Email',
                  v_rt_all_cols(i).email_id,
                  'CORRESPONDENCE',
                  systimestamp,
                  systimestamp,
                  0); 
            END if; 
                  vstep_no  := '6.11';
                  vtable_nm := 'before chop';
             if (v_rt_all_cols(i).ACCOUNT_NUMBER is not null) then 
                      v_rt_all_cols(i).ACCOUNT_NUMBER := 'XXXX'||substr(trim(v_rt_all_cols(i).ACCOUNT_NUMBER),length(trim(v_rt_all_cols(i).ACCOUNT_NUMBER))-3,4);
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)
              values
                (id_val,
                 'IB.Correspondence.AccountNumberMasked',
                 v_rt_all_cols(i).ACCOUNT_NUMBER);
             end if;
                  vstep_no  := '6.1';
                  vtable_nm := 'before stateday';
             if (v_rt_all_cols(i).crr_day is not null) then 
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)
              values
                (id_val,
                 --'IB.Correspondence.Date.Day',
                 'IB.Crsp.Date.Day',
                 v_rt_all_cols(i).crr_day);
             end if;
                  vstep_no  := '6.2';
                  vtable_nm := 'before statemth';
             if (v_rt_all_cols(i).crr_month is not null) then 
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)
              values
                (id_val,
                 --'IB.Correspondence.Date.Month',
                 'IB.Crsp.Date.Month',
                 v_rt_all_cols(i).crr_month);
             end if;
                  vstep_no  := '6.3';
                  vtable_nm := 'before stateyear';
             if (v_rt_all_cols(i).crr_year is not null) then 
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)
              values
                (id_val,
                 --'IB.Correspondence.Date.Year',
                 'IB.Crsp.Date.Year',
                 v_rt_all_cols(i).crr_year);
             end if;
                  vstep_no  := '7';
                  vtable_nm := 'before type';
               if (v_rt_all_cols(i).product_type is not null) then
                  insert into child_tab
                     (COM_ID,                                            
                     KEY,                                                                                                                                        
                     VALUE)
                  values
                    (id_val,
                     'IB.Product.ProductName',
                   v_rt_all_cols(i).product_type);
                end if;
                  vstep_no  := '9';
                  vtable_nm := 'before title';         
              if (trim(v_rt_all_cols(i).title) is not null) then
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE )
              values
                (id_val,
                 'IB.Customer.Title',
                 trim(v_rt_all_cols(i).title));
              end if;
                  vstep_no  := '10';
                  vtable_nm := 'before surname';
              if (v_rt_all_cols(i).surname is not null) then
                insert into child_tab
                   (COM_ID,                                            
                   KEY,                                                                                                                                          
                   VALUE)
                values
                  (id_val,
                  'IB.Customer.LastName',
                  v_rt_all_cols(i).surname);
              end if;
                            vstep_no  := '12';
                            vtable_nm := 'before postcd';
              if (trim(v_rt_all_cols(i).POSTCODE) is not null) then
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)                              
               values
                (id_val,
                 'IB.Customer.Addr.PostCodeMasked',
                  substr(replace(v_rt_all_cols(i).POSTCODE,' ',''),length(replace(v_rt_all_cols(i).POSTCODE,' ',''))-2,3));
              end if;
                            vstep_no  := '13';
                            vtable_nm := 'before subject';
              if (trim(v_rt_all_cols(i).SUBJECT) is not null) then
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)                              
               values
                (id_val,
                 'IB.Correspondence.Subject',
                  v_rt_all_cols(i).subject);
              end if;
                            vstep_no  := '14';
                            vtable_nm := 'before inactivity';
              if (trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) is null or
                  trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '3' or
                  trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '6' or
                  trim(v_rt_all_cols(i).UNREAD_CORRES_PERIOD) = '9') then
              insert into child_tab
                 (COM_ID,                                            
                 KEY,                                                                                                                                            
                 VALUE)                              
               values
                (id_val,
                 'IB.Correspondence.Inactivity',
                  v_rt_all_cols(i).UNREAD_CORRES_PERIOD);
              end if;
                          vstep_no  := '14.1';
                          vtable_nm := 'after notfound';
        end if;
                          vstep_no  := '15';
                          vtable_nm := 'after notfound';
        END LOOP;
        end loop;
                          vstep_no  := '16';
                          vtable_nm := 'before closecur';
        CLOSE stg_cursor;
                          vstep_no  := '17';
                          vtable_nm := 'before commit';
        DELETE FROM table_stg;
      COMMIT;
                          vstep_no  := '18';
                          vtable_nm := 'after commit';
    EXCEPTION
    WHEN OTHERS THEN
      ROLLBACK;
      success_flag := 1;
      vsql_code := SQLCODE;
      vsql_errm := SUBSTR(sqlerrm,1,200);
      error_logging_pkg.inserterrorlog('samp',vsql_code,vsql_errm, vtable_nm,vstep_no);
      RAISE_APPLICATION_ERROR (-20011, 'samp '||vstep_no||' SQLERRM:'||SQLERRM);
    end;
    Thanks

    Its bit urgent
    NO - it is NOT urgent. Not to us.
    If you have an urgent problem you need to hire a consultant.
    I have a performance issue in the below code,
    Maybe you do and maybe you don't. How are we to really know? You haven't posted ANYTHING indicating that a performance issue exists. Please read the FAQ for how to post a tuning request and the info you need to provide. First and foremost you have to post SOMETHING that actually shows that a performance issue exists. Troubleshooting requires FACTS not just a subjective opinion.
    where i am trying to insert the data from table_stg into target_tab and in parent_tab tables and then to child tables via cursor with bulk collect .the target_tab and parent_tab are huge tables and have a row wise trigger enabled on it .the trigger is mandatory . This timetaken for this block to execute is 5000 seconds.Now my requirement is to reduce it to 5 to 10 mins.
    Personally I think 5000 seconds (about 1 hr 20 minutes) is very fast for processing 800 trillion rows of data into parent and child tables. Why do you think that is slow?
    Your code has several major flaws that need to be corrected before you can even determine what, if anything, needs to be tuned.
    This code has the EXIT statement at the beginning of the loop instead of at the end
        FETCH stg_cursor BULK COLLECT INTO v_rt_all_cols LIMIT limit_in;
                  vstep_no  := '4';
                  vtable_nm := 'after fetch';
    --EXIT WHEN v_rt_all_cols.COUNT = 0;
        EXIT WHEN stg_cursor%NOTFOUND;
    The correct place for the %NOTFOUND test when using BULK COLLECT is at the END of the loop; that is, the last statement in the loop.
    You can use a COUNT test at the start of the loop but ironically you have commented it out and have now done it wrong. Either move the NOTFOUND test to the end of the loop or remove it and uncomment the COUNT test.
    WHEN OTHERS THEN
      ROLLBACK;
    That basically says you don't even care what problem occurs or whether the problem is for a single record of your 10,000 in the collection. You pretty much just throw away any stack trace and substitute your own message.
    Your code also has NO exception handling for any of the individual steps or blocks of code.
    The code you posted also begs the question of why you are using NAME=VALUE pairs for child data rows? Why aren't you using a standard relational table for this data?
    As others have noted you are using slow-by-slow (row by row processing). Let's assume that PL/SQL, the bulk collect and row-by-row is actually necessary.
    Then you should be constructing the parent and child records into collections and then inserting them in BULK using FORALL.
    1. Create a collection for the new parent rows
    2. Create a collection for the new child rows
    3. For each set of LIMIT source row data
      a. empty the parent and child collections
      b. populate those collections with new parent/child data
      c. bulk insert the parent collection into the parent table
      d. bulk insert the child collection into the child table
    And unless you really want to either load EVERYTHING or abandon everything you should use bulk exception handling so that the clean data gets processed and only the dirty data gets rejected.

  • Dbms_output.put_line not printing in inner for loop using a parameter

    I cannot get the inner loop to print output. I can run both loops independent (hardcoding a value for the inner loop) Any help is apprecicated... Listed is the code
    set serveroutput on
    DECLARE
    cursor ACCNO_CUR is
    select accession_number from didb_studies where insert_time > to_date('02-JUN-12');
    cursor PATH_CUR (p1_accno VARCHAR2) is
    select distinct l.FILE_SYSTEM || '/' ||
    substr(LPAD(s.PATIENT_DB_UID, 12, '0'),1,3) || '/' ||
    substr(LPAD(s.PATIENT_DB_UID, 12, '0'),4,3) || '/' ||
    substr(LPAD(s.PATIENT_DB_UID, 12, '0'),7,3) || '/' ||
    substr(LPAD(s.PATIENT_DB_UID, 12, '0'),10,3) || '/' ||
    s.STUDY_DB_UID || '/' || i.SERIES_DB_UID || '/'||
    i.RAW_IMAGE_DB_UID || '.img' as FULLY_QUALIFIED_IMAGE_NAME
    , l.image_size
    , i.image_need_backup
    , i.sop_class_uid
    from medistore.didb_studies s
    , medistore.didb_raw_images_table i
    , medistore.didb_image_locations l
    where s.accession_number = 'p1_accno'
    and s.study_db_uid = i.study_db_uid
    and i.raw_image_db_uid = l.raw_image_db_uid
    and l.file_system is not null and INSTR(l.file_system, '.img') = 0
    UNION
    select distinct(l.FILE_SYSTEM) as FULLY_QUALIFIED_IMAGE_NAME
    , l.image_size
    , i.image_need_backup
    , i.sop_class_uid
    from medistore.didb_studies s, medistore.didb_raw_images_table i,
    medistore.didb_image_locations l
    where s.accession_number = 'p1_accno'
    and s.study_db_uid = i.study_db_uid
    and i.raw_image_db_uid = l.raw_image_db_uid
    and l.file_system is not null and INSTR(l.file_system, '.img') > 0
    order by 1;
    BEGIN
    FOR accno_rec in accno_cur LOOP
    DBMS_OUTPUT.put_line('ACCESSION_NUMBER is: '|| accno_rec.accession_number);
    FOR path_rec in path_cur(accno_rec.accession_number) LOOP
    DBMS_OUTPUT.put_line('Inner loop accession_number is :'||accno_rec.accession_number);
    DBMS_OUTPUT.put_line('Full path is : ' || path_rec.FULLY_QUALIFIED_IMAGE_NAME);
    END LOOP;
    END LOOP;
    END;

    Maybe
    DECLARE
      cursor ACCNO_CUR is
        select accession_number
          from didb_studies
         where insert_time > to_date('02-JUN-12');
      cursor PATH_CUR (p1_accno VARCHAR2) is
        select distinct
               l.FILE_SYSTEM || '/' ||
               substr(LPAD(s.PATIENT_DB_UID, 12, '0'),1,3) || '/' ||
               substr(LPAD(s.PATIENT_DB_UID, 12, '0'),4,3) || '/' ||
               substr(LPAD(s.PATIENT_DB_UID, 12, '0'),7,3) || '/' ||
               substr(LPAD(s.PATIENT_DB_UID, 12, '0'),10,3) || '/' ||
               s.STUDY_DB_UID || '/' || i.SERIES_DB_UID || '/'||
               i.RAW_IMAGE_DB_UID || '.img' as FULLY_QUALIFIED_IMAGE_NAME,
               l.image_size,
               i.image_need_backup,
               i.sop_class_uid
          from medistore.didb_studies s,
               medistore.didb_raw_images_table i,
               medistore.didb_image_locations l
         where s.accession_number = to_number(p1_accno) /* to_char(s.accession_number) = p1_accno */
           and s.study_db_uid = i.study_db_uid
           and i.raw_image_db_uid = l.raw_image_db_uid
           and l.file_system is not null
           and INSTR(l.file_system, '.img') = 0
        UNION
        select distinct
               l.FILE_SYSTEM as FULLY_QUALIFIED_IMAGE_NAME,
               l.image_size,
               i.image_need_backup,
               i.sop_class_uid
          from medistore.didb_studies s,
               medistore.didb_raw_images_table i,
               medistore.didb_image_locations l
         where s.accession_number = to_number(p1_accno) /* to_char(s.accession_number) = p1_accno */
           and s.study_db_uid = i.study_db_uid
           and i.raw_image_db_uid = l.raw_image_db_uid
           and l.file_system is not null and INSTR(l.file_system, '.img') > 0
         order by 1;
    BEGIN
      FOR accno_rec in accno_cur
      LOOP
        DBMS_OUTPUT.put_line('ACCESSION_NUMBER is: '|| accno_rec.accession_number);
        FOR path_rec in path_cur(accno_rec.accession_number)
        LOOP
          DBMS_OUTPUT.put_line('Inner loop accession_number is :'||accno_rec.accession_number);
          DBMS_OUTPUT.put_line('Full path is : ' || path_rec.FULLY_QUALIFIED_IMAGE_NAME);
        END LOOP;
      END LOOP;
    END;Regards
    Etbin

  • For loop- seems to be just going to last value

    Hi guys, carrying on from the thread I created yesterday I have managed to get the socket working between my server and my client, but I am having an issue when re-constructing a string that is being sent from the client to the server. I am talking about the for loop in line 151, which seems to just going straight to the last value of the for loop and thus the board isn't being reconstructed properly.
    I'm including both the server and client code which just needs to compiled (host is set to localhost on port 4500) and you will see what I mean after inputting a move from the client. Can anyone spot the problem?
    Server code
    import java.io.*;
    import java.net.*;
    import javax.swing.JOptionPane;
    class Server
         public static void main (String []args) throws IOException
              try
                   Server();     
              catch (IOException ex)
         public static void Server () throws IOException
              ServerSocket serverSocket=null;
              int portNo=4500;
              System.out.println("Starting");
              try
                   serverSocket=new ServerSocket(portNo);     
              catch (IOException ex)
                   System.err.println("Could not create socket on port" +portNo);
                   System.exit(1);
              System.out.println("Socket listening");
              Socket clientSocket=null;
              try
                   clientSocket=serverSocket.accept();
              catch (IOException ex)
                   System.out.println("Accept failed");
                   System.exit(1);
              PrintWriter out= new PrintWriter(clientSocket.getOutputStream(), true);
              BufferedReader in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
              //coordinates
              String coordinates[] [] = new String [8] [8];
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        if ((i%2!=0)&&(j%2!=0))
                             coordinates[i] [j]="#";
                        else if ((i%2!=0)&&(j%2==0))
                             coordinates[i] [j]=" ";
                        else if ((i%2==0)&&(j%2!=0))
                             coordinates[i] [j]=" ";
                        else
                             coordinates[i] [j]="#";
              coordinates[0][0]="R";
              coordinates[0][1]="N";
              coordinates[0][2]="B";
              coordinates[0][3]="Q";
              coordinates[0][4]="K";
              coordinates[0][5]="B";
              coordinates[0][6]="N";
              coordinates[0][7]="R";
              for (int i=0;i<8;i++)
                   coordinates[1]="P";
              coordinates[7][0]="r";
              coordinates[7][1]="n";
              coordinates[7][2]="b";
              coordinates[7][3]="q";
              coordinates[7][4]="k";
              coordinates[7][5]="b";
              coordinates[7][6]="n";
              coordinates[7][7]="r";
              for (int i=0;i<8;i++)
                   coordinates[6][i]="p";
              Board board1=new Board(coordinates);
              boolean gameStart=true;
              String coord="";
              String originX="";
              String originY="";
              String destinationX="";
              String destinationY;
              while (gameStart)
                   System.out.println("trying to read from client");
                   String input="";
                   try
                        input=in.readLine();     
                        System.out.println(input);
                   catch (IOException ex)
                        System.out.println("Read failed");
                        System.exit(1);
                   originX=input.substring(65);
                   originY=input.substring(66);     
                   destinationX=input.substring(67);
                   destinationY=input.substring(68);
                   coord=input.substring(0,64);
                   System.out.println(coord);
                   for (int p=0;p<64;p++)
                        System.out.println(p);
                        for (int i=0;i<8;i++)
                             for (int j=0;j<8;j++)
                                  coordinates [i] [j]=coord.substring(p);
                                  if (i==(Integer.parseInt(originX))&&(j==(Integer.parseInt(originY))))
                                       String piece="";
                                       piece=coordinates [i] [j];
                                       if ((i%2!=0)&&(j%2!=0))
                                            coordinates[i] [j]="#";
                                       else if ((i%2!=0)&&(j%2==0))
                                            coordinates[i] [j]=" ";
                                       else if ((i%2==0)&&(j%2!=0))
                                            coordinates[i] [j]=" ";
                                       else
                                            coordinates[i] [j]="#";
                                       for (int s=0;s<8;s++)
                                            for (int t=0;t<8;t++)
                                                 if (s==(Integer.parseInt(destinationX))&&(t==(Integer.parseInt(destinationY))))
                                                      coordinates [s] [t]=piece;
                   board1.printBoard(coordinates);
              out.close();
              in.close();     
              clientSocket.close();
              serverSocket.close();          
    class Board
         boolean gameStart=true;
         public Board()
         public Board(String [] [] coordinates)
              printBoard(coordinates);
         String [] [] getCoOrdinates(String [] [] coordinates)
              return coordinates;
         public static void update (String coordinates [] [])
              printBoard(coordinates);
         public static void printBoard(String coordinates[] [])
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        System.out.print(coordinates[i][j]);
                   System.out.println();
    }Client code:import java.io.*;
    import java.net.*;
    import javax.swing.JOptionPane;
    class Client
         public static void main (String [] args) throws IOException
              Socket socket=null;
              PrintWriter out=null;
              BufferedReader in=null;
              String serverLocation="localhost";
              int portNo=4500;
              System.out.println("Starting");
              try
                   socket= new Socket (serverLocation,portNo);
                   out= new PrintWriter(socket.getOutputStream(),true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              catch (UnknownHostException ex)
                   System.out.println("Cannot find" + serverLocation);
                   System.exit(1);     
              catch (IOException ex1)
                   System.out.println("IO problem");
                   System.exit(1);
              System.out.println("Connected");
              //coordinates
              String coordinates[] [] = new String [8] [8];
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        if ((i%2!=0)&&(j%2!=0))
                             coordinates[i] [j]="#";
                        else if ((i%2!=0)&&(j%2==0))
                             coordinates[i] [j]=" ";
                        else if ((i%2==0)&&(j%2!=0))
                             coordinates[i] [j]=" ";
                        else
                             coordinates[i] [j]="#";
              coordinates[0][0]="R";
              coordinates[0][1]="N";
              coordinates[0][2]="B";
              coordinates[0][3]="Q";
              coordinates[0][4]="K";
              coordinates[0][5]="B";
              coordinates[0][6]="N";
              coordinates[0][7]="R";
              for (int i=0;i<8;i++)
                   coordinates[1][i]="P";
              coordinates[7][0]="r";
              coordinates[7][1]="n";
              coordinates[7][2]="b";
              coordinates[7][3]="q";
              coordinates[7][4]="k";
              coordinates[7][5]="b";
              coordinates[7][6]="n";
              coordinates[7][7]="r";
              for (int i=0;i<8;i++)
                   coordinates[6][i]="p";
              Board board1=new Board(coordinates);
              boolean gameStart=true;
              String coord="";
              while (gameStart)
                   String originMove=JOptionPane.showInputDialog(null,"Client Origin Move","Enter in origin of piece",JOptionPane.QUESTION_MESSAGE);
                   String destinationMove=JOptionPane.showInputDialog(null,"Client Destination Move","Enter in destination of piece",JOptionPane.QUESTION_MESSAGE);
                   for (int i=0;i<8;i++)
                        for (int j=0;j<8;j++)
                             coord=coord+coordinates[i][j];
                   System.out.println(coord);
                   out.println(coord+originMove+destinationMove);
                   System.out.println("passed");
              out.close();
              in.close();
              socket.close();
    class Board
         boolean gameStart=true;
         public Board()
         public Board(String [] [] coordinates)
              printBoard(coordinates);
         String [] [] getCoOrdinates(String [] [] coordinates)
              return coordinates;
         public static void update (String coordinates [] [])
              printBoard(coordinates);
         public static void printBoard(String coordinates[] [])
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        System.out.print(coordinates[i][j]);
                   System.out.println();
    }Cheers,
    Ben                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    jverd wrote:
    p595659 wrote:
    1) I don't think that even compiles. Since you're catching IOException, your throws clause is bogus--that method can never throw IOE.I have removed the try and catch statements in the main method. I cannot, however get rid of the throws IOException in the main method other my program won't compile.Right. Don't catch it, since you're not handling it. Just declare that it throws it.
    Indeed, this is what I have done :)
    >
    3) Don't name methods the same as your class name.See answer to 4.
    4) Start method names with lowercase letters.
    try
    serverSocket=new ServerSocket(portNo);     
    catch (IOException ex)
    System.err.println("Could not create socket on port" +portNo);
    System.exit(1);
    ServerSocket is a part of the java.net package. I am just creating an instance of it. http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html
    I don't know what you're talking about. You had a class named Server and a method named Server. That's confusing.Changed- I didn't spot it, so I have named it startServer now.
    >
    5) There's almost no point to ever calling System.exit. Here, again, since you're not
    actually handling the exception, don't bother catcing it.Sorry, but this was how I was taught when I started java. My understanding is that System.exit properly terminated applications so this freed up memory so it's abit of a habit of mine, is this wrong to do in this instance?Calling it in response to an exception is wrong. It's not that method's job to decide to shut down the VM. Just let the exception bubble up (or else handle it properly). You do not need to call System.exit to free up memory. It's freed up automatically when the VM exits. The OS takes care of that, without any help from you.Removed- thanks for clearing that up for me :)
    JacobsB wrote:
    line 151 of the server code or client code?Line 151 of my server code. My client is working fine up to this step of the programming I have done- it's just the server part I'm having issues with. You can compile and run the client fine- you can compile the server but as explained in the original post, I'm having a logical error when redrawing the board when it gets the 68 charecter string from the client (first 64 charecters are for the board, then the original position (x and y respectively), followed up the new position (x and y respectively again).
    I'm including an updated version of the code, after all the comments above so we have an updated version for trying to solve the problem I'm having. The client code does not need to be updated as it has not changed yet, so you can use the code in the original post.
    import java.io.*;
    import java.net.*;
    import javax.swing.JOptionPane;
    class Server
         public static void main (String []args) throws IOException
              startServer();     
         public static void startServer () throws IOException
              ServerSocket serverSocket=null;
              int portNo=4500;
              System.out.println("Starting");
              try
                   serverSocket=new ServerSocket(portNo);     
              catch (IOException ex)
                   System.err.println("Could not create socket on port" +portNo);
                   ex.printStackTrace();
              System.out.println("Socket listening");
              Socket clientSocket=null;
              try
                   clientSocket=serverSocket.accept();
              catch (IOException ex)
                   System.out.println("Accept failed");
                   ex.printStackTrace();
              PrintWriter out= new PrintWriter(clientSocket.getOutputStream(), true);
              BufferedReader in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
              //coordinates
              String coordinates[] [] = new String [8] [8];
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        if ((i%2!=0)&&(j%2!=0))
                             coordinates[i] [j]="#";
                        else if ((i%2!=0)&&(j%2==0))
                             coordinates[i] [j]=" ";
                        else if ((i%2==0)&&(j%2!=0))
                             coordinates[i] [j]=" ";
                        else
                             coordinates[i] [j]="#";
              coordinates[0][0]="R";
              coordinates[0][1]="N";
              coordinates[0][2]="B";
              coordinates[0][3]="Q";
              coordinates[0][4]="K";
              coordinates[0][5]="B";
              coordinates[0][6]="N";
              coordinates[0][7]="R";
              for (int i=0;i<8;i++)
                   coordinates[1]="P";
              coordinates[7][0]="r";
              coordinates[7][1]="n";
              coordinates[7][2]="b";
              coordinates[7][3]="q";
              coordinates[7][4]="k";
              coordinates[7][5]="b";
              coordinates[7][6]="n";
              coordinates[7][7]="r";
              for (int i=0;i<8;i++)
                   coordinates[6][i]="p";
              Board board1=new Board(coordinates);
              boolean gameStart=true;
              String coord="";
              String originX="";
              String originY="";
              String destinationX="";
              String destinationY;
              while (gameStart)
                   System.out.println("trying to read from client");
                   String input="";
                   try
                        input=in.readLine();     
                        System.out.println(input);
                   catch (IOException ex)
                        System.out.println("Read failed");
                        ex.printStackTrace();
                   coord=input.substring(0,64);                    
                   originX=input.substring(64,65);
                   originY=input.substring(65,66);     
                   destinationX=input.substring(66,67);
                   destinationY=input.substring(67,68);
                   System.out.println(coord);
                   for (int p=0;p<64;p++)
                        System.out.println(p);
                        for (int i=0;i<8;i++)
                             for (int j=0;j<8;j++)
                                  coordinates [i] [j]=coord.substring(p);
                                  if (i==Integer.parseInt(originX)&&(j==(Integer.parseInt(originY))))
                                       String piece="";
                                       piece=coordinates [i] [j];
                                       if ((i%2!=0)&&(j%2!=0))
                                            coordinates[i] [j]="#";
                                       else if ((i%2!=0)&&(j%2==0))
                                            coordinates[i] [j]=" ";
                                       else if ((i%2==0)&&(j%2!=0))
                                            coordinates[i] [j]=" ";
                                       else
                                            coordinates[i] [j]="#";
                                       for (int s=0;s<8;s++)
                                            for (int t=0;t<8;t++)
                                                 if (s==(Integer.parseInt(destinationX))&&(t==(Integer.parseInt(destinationY))))
                                                      coordinates [s] [t]=piece;
                   board1.printBoard(coordinates);
              out.close();
              in.close();     
              clientSocket.close();
              serverSocket.close();          
    class Board
         boolean gameStart=true;
         public Board()
         public Board(String [] [] coordinates)
              printBoard(coordinates);
         String [] [] getCoOrdinates(String [] [] coordinates)
              return coordinates;
         public static void update (String coordinates [] [])
              printBoard(coordinates);
         public static void printBoard(String coordinates[] [])
              for (int i=0;i<8;i++)
                   for (int j=0;j<8;j++)
                        System.out.print(coordinates[i][j]);          
                   System.out.println();
    }Ben                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can i use the same cursor in a loop fro multipletimes.

    I am using two cursors.One to fetch sites and the other to fetch participants under each site.I am performing some job with that participants data.Now the problem is i am using the 2nd cursor in a loop.So it fetches the data of participants falling under one state.But when it comes to the second state,as the second cursor is already open it is unable to fetch the records.Please help me .How can i use the same cursor in a loop fro multipletimes.
    I am sending the code which i have written in When-Button-Pressed-Trigger...
    declare
         sid number;
         pid number;
    cursor csid is select distinct(site_id) from cyber_ppt;
    cursor cpid is select pc_id,st_dt,ed_dt from cyber_ppt where site_id = sid;
         stdt varchar2(10);
         eddt varchar2(10);
         nom number;
         stmonth varchar2(10);
         edmonth varchar2(10);
         cjan number:=0;
         cfeb number:=0;
         cmar number:=0;
         capr number:=0;
         cmay number:=0;
         cjun number:=0;
         cjul number:=0;
         caug number:=0;
         csep number:=0;
         coct number:=0;
         cnov number:=0;
         cdec number:=0;
         i number:=1;
    begin
         open csid ;
         loop
         fetch csid into sid;
              exit when csid %notfound;
              message(sid);
         open cpid;
         loop
         fetch cpid into pid,stdt,eddt ;
         exit when cpid %notfound;
         message(sid||'-'||pid);
         stmonth:=substr(stdt,4,3);
         edmonth:=substr(eddt,4,3);
         nom:= months_between(eddt,stdt);
    while i <= round(nom)
         loop
         stmonth:=substr(stdt,4,3);
    if stmonth='JAN' then
              cjan:=cjan+1;
    elsif stmonth='FEB' then
              cfeb:=cfeb+1;
    elsif stmonth='MAR' then
              cmar:=cmar+1;
    elsif stmonth='APR' then
              capr:=capr+1;
    elsif stmonth='MAY' then
              cmay:=cmay+1;
    elsif stmonth='JUN' then
              cjun:=cjun+1;
    elsif stmonth ='JUL' then
              cjul:=cjul+1;
    elsif stmonth ='AUG' then
              caug:=caug+1;
    elsif stmonth ='SEP' then
              csep:=csep+1;
    elsif stmonth ='OCT' then
              coct:=coct+1;
    elsif stmonth ='NOV' then
              cnov:=cnov+1;
    elsif stmonth ='DEC' then
              cdec:=cdec+1;
    end if;
         stdt:=add_months(stdt,1);
         i:=i+1;
         end loop;
         end loop;
         end loop;
         end;
         

    try this /* untested */
    DECLARE
    sid           NUMBER;
    pid           NUMBER;
    CURSOR csid IS SELECT DISTINCT(site_id) FROM cyber_ppt;
    CURSOR cpid(nSid NUMBER) is SELECT pc_id,st_dt,ed_dt FROM cyber_ppt WHERE site_id = nSid;
    stdt        VARCHAR2(10);
    eddt        VARCHAR2(10);
    nom         NUMBER;
    stmonth     VARCHAR2(10);
    edmonth     VARCHAR2(10);
    cjan         NUMBER:=0;
    cfeb         NUMBER:=0;
    cmar         NUMBER:=0;
    capr         NUMBER:=0;
    cmay         NUMBER:=0;
    cjun         NUMBER:=0;
    cjul         NUMBER:=0;
    caug         NUMBER:=0;
    csep         NUMBER:=0;
    coct         NUMBER:=0;
    cnov         NUMBER:=0;
    cdec         NUMBER:=0;
    i            NUMBER:=1;
    BEGIN
    FOR rec IN csid
    LOOP
                      sid := rec.csid;
    FOR cRec IN cpid(sid)
    LOOP
                     pid := cRec.pc_id;
                     stdt := cRec.st_dt;
                     eddt := cRec.ed_dt;
    stmonth:=  SUBSTR(stdt,4,3);
    edmonth:= SUBSTR(eddt,4,3);
    nom:= months_between(eddt,stdt);
    WHILE i <= round(nom)
    LOOP
              stmonth := SUBSTR(stdt,4,3);
    IF stmonth='JAN'
    THEN
             cjan:=cjan+1;
    ELSIF stmonth='FEB' THEN
             cfeb:=cfeb+1;
    ELSIF stmonth='MAR' THEN
              cmar:=cmar+1;
    ELSIF stmonth='APR' THEN
              capr:=capr+1;
    ELSIF stmonth='MAY' THEN
              cmay:=cmay+1;
    ELSIF stmonth='JUN' THEN
              cjun:=cjun+1;
    ELSIF stmonth ='JUL' THEN
              cjul:=cjul+1;
    ELSIF stmonth ='AUG' THEN
              caug:=caug+1;
    ELSIF stmonth ='SEP' THEN
              csep:=csep+1;
    ELSIF stmonth ='OCT' THEN
              coct:=coct+1;
    ELSIF stmonth ='NOV' THEN
              cnov:=cnov+1;
    ELSIF stmonth ='DEC' THEN
              cdec:=cdec+1;
    END IF;
             stdt:=add_months(stdt,1);
             i:=i+1;
    END LOOP;
    END LOOP;
    END LOOP;
    END;

  • Multiple Select List looping thru PL/SQL function body returning SQL query

    Hi,
    I have a Multiple Select List. I want to loop through the values from the Select List and process them in a PL/SQL function body returning a SQL query. Currently, my code only returns the SQL SELECT results of one item in the select list. How do I change my code to make it return the results of all of the items in the select list? (I tested it and it is definitely picking up all the values in the select list).
    <b>
    DECLARE
    selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
    s   VARCHAR2(20);
    q varchar2(32767);
    BEGIN
    selected_items := HTMLDB_UTIL.STRING_TO_TABLE(:P50_SELECTED_INSTRUMENTS);
    -- htp.p('COUNT: '||selected_items.count);
      FOR i in 1..selected_items.count LOOP
      s := TO_CHAR(selected_items(i));
    -- htp.p('First: '||s);
    -- htp.p('Second: '||:s);
    -- htp.p('Third: '||TO_CHAR(selected_items(i)));
      q:= 'SELECT  '||
    'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
    'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
    ' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
    'sum(orig_intrl) orig_intrl, '||
    'sum(orig_extrl) orig_extrl, '||
    'sum(recv_intrl) recv_intrl, '||
    'sum(recv_extrl) recv_extrl '||
    'FROM line_usage_sum_view '||
    'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''' || s ||'%'' '||
    --'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
    'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
    'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
    'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
    'AND '||
    :SORTFIELD||' BETWEEN '||
    'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
    'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
    'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
    -- htp.p('SQL query: '||q);
      RETURN q;
      END LOOP;
    END;</b>
    Thank you,
    Laura

    Laura,
    First, I would be careful of introducing SQL Injection possibilities. Any time I see
    'Select ... ' || :P123_FOO || ' ... '
    I worry about sql injection. In your case you are converting :P50_SELECTED_INSTRUMENTS into selected_items and then selected_items into s. So when I see
    'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''' || s ||'%'' '||
    I think, "I could use sql Injection and hack this."
    So, I would do some validation on :P50_SELECTED_INSTRUMENTS or some other method to avoid this.
    I'm not certain I understand your query. Do you really intend to allow the user to select the beginning of a string and then find all rows that start with that string? Or, do you just want to let them find when it matches the string. This is one way if you want to do matching:
    DECLARE
    selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
    s VARCHAR2(32767);
    q varchar2(32767);
    BEGIN
    -- Change the : separate string to be comma separated with quoted strings
    s := '''' || replace(:P50_SELECTED_INSTRUMENTS, ',', ''',''')|| '''' ;
    -- htp.p('COUNT: '||selected_items.count);
    q:= 'SELECT '||
    'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
    'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
    ' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
    'sum(orig_intrl) orig_intrl, '||
    'sum(orig_extrl) orig_extrl, '||
    'sum(recv_intrl) recv_intrl, '||
    'sum(recv_extrl) recv_extrl '||
    'FROM line_usage_sum_view '||
    'WHERE TO_CHAR(orig_geo_loc_sys) in (' || s ||' ) '||
    --'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
    'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
    'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
    'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
    'AND '||
    :SORTFIELD||' BETWEEN '||
    'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
    'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
    'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
    -- htp.p('SQL query: '||q);
    RETURN q;
    END;
    If you want to do something more like you originally stated, try this:
    DECLARE
    selected_items HTMLDB_APPLICATION_GLOBAL.VC_ARR2;
    s VARCHAR2(20);
    q varchar2(32767);
    BEGIN
    selected_items := HTMLDB_UTIL.STRING_TO_TABLE(:P50_SELECTED_INSTRUMENTS);
    -- htp.p('COUNT: '||selected_items.count);
    q:= 'SELECT '||
    'SUBSTR(orig_geo_loc_sys,1,INSTR(orig_geo_loc_sys,''-'')-1) AS INSTRUMENT, '||
    'SUBSTR(orig_geo_loc_sys,INSTR(orig_geo_loc_sys,''-'')+1, LENGTH'||
    ' (orig_geo_loc_sys)) AS ORIG_LINENUM, '||
    'sum(orig_intrl) orig_intrl, '||
    'sum(orig_extrl) orig_extrl, '||
    'sum(recv_intrl) recv_intrl, '||
    'sum(recv_extrl) recv_extrl '||
    'FROM line_usage_sum_view '||
    'WHERE 1=1 ';
    FOR i in 1..selected_items.count LOOP
    s := TO_CHAR(selected_items(i));
    q := q || ' and TO_CHAR(orig_geo_loc_sys) LIKE '''|| s ||'%'' ' ;
    END LOOP;
    q := q || ||'%'' '||
    --'WHERE TO_CHAR(orig_geo_loc_sys) LIKE ''2213003%'' '||
    'AND switch_id = ''' || :P1_SWITCH_ID || ''' ' ||
    'AND call_start_date > TO_DATE(''30-NOV-1999'') ' ||
    'AND call_clear_time > TO_DATE(''30-NOV-1999'') '||
    'AND '||
    :SORTFIELD||' BETWEEN '||
    'TO_DATE(:STARTDATE,''dd-MON-YYYY HH24:MI'') AND '||
    'TO_DATE(:STOPDATE, ''dd-MON-YYYY HH24:MI'') '||
    'GROUP BY GROUPING SETS (orig_geo_loc_sys)';
    -- htp.p('SQL query: '||q);
    RETURN q;
    END;
    Hope this helps...
    Anton

  • Infinite loop problem

    Hi there,
    This is the second time I have posted this problem, as the last solution I was offered did not seem to work. Here is the problem:
    I have written a method to search through a text file for a word and replace it with another word. That word can either be on its own in the document or as part of another word. So, if the search word was "foot" and the replace word was "dog", the word "football" in the document would become "dogball".
    This method works fine, except for when the replace word is the same as the search word. Basically, if someone searched for "dog" and wanted to replace it with "dog dog" or even just "dog", the program goes into an infinite loop. I understand why it is doing this, but I don't know how to prevent it from happening.
    Now, to make it worse I have to stick to this array style structure and method of solving the problem. I know there is a way to do this by building temporary strings and then concatenating them at the end and returning them to their previous position in the array. The reason I know this is because a friend of mine has managed it. She also happens to be a girl.
    So, I am asking you all to assist in defending men's intelligence by helping me see where I am going wrong in this method. Please.
    Here is the method:
    // Search the document for a string and replace it with another string        
         public String [] SearchReplace() {
              // Declare variables to be used in the method
              String SecondSubstring;
              String FirstSubstring;
              int ReplaceNumber = 0;
              // Loop through the lines of text stored as strings contained in the array
              for (int i = 0; i < NumberOfLines; i++) {
                        // As long as the string contains an instance of the search string, run the method                    
                        while (StrArray.indexOf(SearchW) >= 0) {
                             // Make a string of all the characters after the search word
                             SecondSubstring = StrArray[i].substring(StrArray[i].indexOf(SearchW) + SearchW.length());
                             // Make a string of all the characters before the search word
                             FirstSubstring = StrArray[i].substring(0, StrArray[i].indexOf(SearchW));
                             // Concatenate FirstSubstring with the replace word to make a new string
                             String FirstHalf = FirstSubstring.concat(ReplaceW);
                             // Concatenate the new string with SecondSubstring to make the whole replaced string
                             String FullString = FirstHalf.concat(SecondSubstring);
                             // Put this altered string back to its original place in the array
                             StrArray[i] = FullString;
                             // Increment ReplaceNumber to count the replacements made
                             ReplaceNumber++;
              // Print the numbers of replacements made
              System.out.println("\nA total of " + ReplaceNumber + " changes made.\n");
              // Display the searched and replaced contents of the file
              return StrArray;
    Any suggestions, pointers or solutions would be much appreciated.
    Thanks very much.

    Doing it the "old fashioned" way:
    You need to keep track of a "from index" so you don't search through parts of the string you've already replaced:
           public static void main(String args[]) {          
              try {     
                   String[] lines = new String[] {
                        "the dog went up the dog hill",
                        "all dogs go to dog heaven",
                        "the dogball takes place on 3rd april"
                   lines = replace(lines, "dog", "dog dog");
                   for (int i = 0; i < lines.length; i++) {
                        System.out.println(lines);
              } catch (Exception e) {
                   e.printStackTrace();
         private static String[] replace(String[] lines, String searchWord, String replaceWord) {
              if (searchWord.equals(replaceWord)) return lines; // nothing to do          
              for (int i = 0; i < lines.length; i++) {
                   int fromIndex = 0; // from index to do indexOf
                   String line = lines[i];
                   while (line.indexOf(searchWord, fromIndex) != -1) {
                        final int index = line.indexOf(searchWord, fromIndex);
                        line = line.substring(0, index) + replaceWord + line.substring(index + searchWord.length());
                        fromIndex = (line.substring(0, index) + replaceWord).length();
                   lines[i] = line; // replace
              return lines;

  • How can I do a loop within a select statement

    This is my query
    Select distinct
    s.First_NM,
    s.Last_nm,
    s.Date_of_birth,
    i.Class_ID,
    i.Enrollment_begn_dt,
    i.Enrollment_end_dt,
    SUBSTR(TO_CHAR(i.Enrollment_begn_dt, 'MMDDYYYY'),1,2) AS MONTH,
    SUBSTR(TO_CHAR(i.Enrollment_end_dt, 'MMDDYYYY'),5,4) AS YEAR,
    CASE WHEN TO_NUMBER(SUBSTR(TO_CHAR(i.Enrollment_begn_dt, 'MMDDYYYY'),1,2)) >= '5'
          THEN (TO_NUMBER(SUBSTR(TO_CHAR(i.Enrollment_begn_dt,'MMDDYYYY'),5,4)) + '1')
           ELSE TO_NUMBER(SUBSTR(TO_CHAR(i.Enrollment_begn_dt,'MMDDYYYY'),5,4)) END AS Enrollment_cycle
    From student s, institution iEnrollment cycles are defined as follows
    05/1/2004 to 04/30/2005 == 2005
    05/1/2005 to 04/30/2006 == 2006
    05/1/2006 to 04/30/2007 == 2007
    05/1/2007 to 04/30/2008 == 2008
    This is the current output
    First_NM       Last_nm     Date_of_birth     Class_ID     Enrollment_begn_dt     Enrollment_end_dt     Enrollment_cycle
    Jake     Brown     11/10/1999     Blue_007         7/10/2004        6/10/2007        2005
    Amy     Burrell     5/1/1999                     Blue_007         1/20/2005        5/1/2005        2005
    Char     Goblin     12/24/1999     Blue_007         3/3/2006        7/10/2020        2006My desired output is - which I am having difficulty creating
    First_NM       Last_nm     Date_of_birth     Class_ID     Enrollment_begn_dt     Enrollment_end_dt     Enrollment_cycle
    Jake     Brown     11/10/1999     Blue_007         7/10/2004        4/30/2005       2005
    Jake     Brown     11/10/1999     Blue_007         5/1/2005        4/30/2006       2006
    Jake     Brown     11/10/1999     Blue_007         5/1/2006        4/30/2007       2007
    Jake     Brown     11/10/1999     Blue_007         5/1/2007        6/10/2007       2008
    Amy     Burrell     5/1/1999                     Blue_007         1/20/2005        5/1/2005       2005
    Char     Goblin     12/24/1999     Blue_007         3/3/2006        4/30/2006       2006
    Char     Goblin     12/24/1999     Blue_007         5/1/2006        4/30/2007       2007
    Char     Goblin     12/24/1999     Blue_007         5/1/2007        4/30/2008       2008
    Char     Goblin     12/24/1999     Blue_007         5/1/2008        4/30/2009       2009I trying to break up each record in the previous table into multiple enrollment cycles based on how it is decribed.
    Also note the last record - the cycle ends at 4/30/2009 ----This is because the enrollment_cycle will only stop at the current year + 1 (i.e if we assume current year to be 2008 then the cut off will be year will be 2009 hence I have 4/30/2009 instead of 7/10/2020
    I am thinking this can be done with a for loop but I am not sure how to do it. without hard coding the dates.
    Please help me!!!!!

    Hi ,
    I forgot the DATE_OF_BIRTH.
    Regards
    Salim.
    WITH t AS
         (SELECT 'Jake' first_nm, 'Brown' last_nm, to_date('11/10/1999','mm/dd/yyyy') date_of_birth,
                 'Blue_007' class_id, to_date('07/10/2004','mm/dd/yyyy') enrollment_begn_dt,
                 to_date('06/10/2007','mm/dd/yyyy') enrollment_end_dt, '2005' enrollment_cycle
            FROM DUAL
          UNION ALL
          SELECT 'Amy', 'Burrell', to_date('05/01/1999','mm/dd/yyyy'), 'Blue_007', to_date('01/20/2005','mm/dd/yyyy'),
                 to_date('05/01/2005','mm/dd/yyyy'), '2005' enrollment_cycle
            FROM DUAL
          UNION ALL
          SELECT 'Char', 'Goblin', to_date('12/24/1999','mm/dd/yyyy'), 'Blue_007', to_date('03/03/2006','mm/dd/yyyy'),
                 to_date('07/10/2020','mm/dd/yyyy'), '2006' enrollment_cycle
            FROM DUAL)
    SELECT FIRST_NM,LAST_NM,DATE_OF_BIRTH,ENROLLMENT_BEGN_DT,ENROLLMENT_END_DT,ENROLLMENT_CYCLE
      FROM T
      MODEL
      RETURN UPDATED ROWS
      PARTITION BY (FIRST_NM,LAST_NM)
      DIMENSION BY (1 ANNEE )
      MEASURES(ENROLLMENT_BEGN_DT,DATE_OF_BIRTH,ENROLLMENT_CYCLE,LEAST(  ENROLLMENT_END_DT, TRUNC(SYSDATE)) ENROLLMENT_END_DT)IGNORE NAV
      (  ENROLLMENT_BEGN_DT[FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT ( YEAR FROM ENROLLMENT_END_DT[1])   INCREMENT 1]  =  TO_DATE(TO_CHAR(ENROLLMENT_BEGN_DT[1],'MM/DD')||'/'||CV(ANNEE),'MM/DD/YYYY'),
         ENROLLMENT_END_DT [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT ( YEAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1]  =  TO_DATE('04/30'||(CASE WHEN EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) = 
                                                                                                                                                                                    EXTRACT ( YEAR FROM ENROLLMENT_END_DT[1])  THEN CV(ANNEE) ELSE CV(ANNEE)+1 END)  ,'MM/DD/YYYY'),
         ENROLLMENT_CYCLE [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT ( YEAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1] =CV(ANNEE) ,
         DATE_OF_BIRTH [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT ( YEAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1] =DATE_OF_BIRTH[1])
    SQL> WITH t AS
      2       (SELECT 'Jake' first_nm, 'Brown' last_nm, to_date('11/10/1999','mm/dd/yyyy') date_of_birth
      3               'Blue_007' class_id, to_date('07/10/2004','mm/dd/yyyy') enrollment_begn_dt,
      4               to_date('06/10/2007','mm/dd/yyyy') enrollment_end_dt, '2005' enrollment_cycle
      5          FROM DUAL
      6        UNION ALL
      7        SELECT 'Amy', 'Burrell', to_date('05/01/1999','mm/dd/yyyy'), 'Blue_007', to_date('01/20/2
    005','mm/dd/yyyy'),
      8               to_date('05/01/2005','mm/dd/yyyy'), '2005' enrollment_cycle
      9          FROM DUAL
    10        UNION ALL
    11        SELECT 'Char', 'Goblin', to_date('12/24/1999','mm/dd/yyyy'), 'Blue_007', to_date('03/03/2
    006','mm/dd/yyyy'),
    12               to_date('07/10/2020','mm/dd/yyyy'), '2006' enrollment_cycle
    13          FROM DUAL)
    14  SELECT FIRST_NM,LAST_NM,DATE_OF_BIRTH,ENROLLMENT_BEGN_DT,ENROLLMENT_END_DT,ENROLLMENT_CYCLE
    15    FROM T
    16    MODEL
    17    RETURN UPDATED ROWS
    18    PARTITION BY (FIRST_NM,LAST_NM)
    19    DIMENSION BY (1 ANNEE )
    20    MEASURES(ENROLLMENT_BEGN_DT,DATE_OF_BIRTH,ENROLLMENT_CYCLE,LEAST(  ENROLLMENT_END_DT, TRUNC(S
    YSDATE)) ENROLLMENT_END_DT)IGNORE NAV
    21    (  ENROLLMENT_BEGN_DT[FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT
    ( YEAR FROM ENROLLMENT_END_DT[1])   INCREMENT 1]  =  TO_DATE(TO_CHAR(ENROLLMENT_BEGN_DT[1],'MM/DD')
    ||'/'||CV(ANNEE),'MM/DD/YYYY'),
    22       ENROLLMENT_END_DT [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT
    ( YEAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1]  =  TO_DATE('04/30'||(CASE WHEN EXTRACT ( YEAR FROM
    ENROLLMENT_BEGN_DT[1]) = 
    23                                                                                                
                                                                                     EXTRACT ( YEAR FROM
    ENROLLMENT_END_DT[1])  THEN CV(ANNEE) ELSE CV(ANNEE)+1 END)  ,'MM/DD/YYYY'),
    24       ENROLLMENT_CYCLE [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT
    ( YEAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1] =CV(ANNEE) ,
    25       DATE_OF_BIRTH [FOR ANNEE FROM   EXTRACT ( YEAR FROM ENROLLMENT_BEGN_DT[1]) TO  EXTRACT ( Y
    EAR FROM ENROLLMENT_END_DT[1])  INCREMENT 1] =DATE_OF_BIRTH[1])
    26    ;
    FIRS LAST_NM DATE_OF_BI ENROLLMENT ENROLLMENT ENRO
    Jake Brown   1999-11-10 2004-07-10 2005-04-30 2004
    Jake Brown   1999-11-10 2005-07-10 2006-04-30 2005
    Jake Brown   1999-11-10 2006-07-10 2007-04-30 2006
    Jake Brown   1999-11-10 2007-07-10 2008-04-30 2007
    Amy  Burrell 1999-05-01 2005-01-20 2005-04-30 2005
    Char Goblin  1999-12-24 2006-03-03 2007-04-30 2006
    Char Goblin  1999-12-24 2007-03-03 2008-04-30 2007
    Char Goblin  1999-12-24 2008-03-03 2009-04-30 2008
    Char Goblin  1999-12-24 2009-03-03 2010-04-30 2009
    9 ligne(s) sélectionnée(s).

Maybe you are looking for

  • Cannot preview ORF files in bridge cs4

    cannot preview ORF files in bridge cs4

  • Flash Video problems on MAC OS X

    I am trying to export a video from Flash CS5 and when it exports there is some artifacting. I discovered this issue in another disscussion on Adobe Flash Forums I had about Flash and After Effects, and someone using the same settings exported the vid

  • Editing images in Adobe Reader

    I have set up a form template in Indesign, using form fields, so that customers can edit their contact information and image.  I know that you can edit this information in Acrobat, but is it possible to edit these things in Adobe Reader?  I have open

  • Publishing Exchange calendar to web without Outlook

    I want to allow my wife to view my Exchange-based calendar remotely (eg. via the web or a third party app). I am aware of the publishing/sharing options in MS Outlook to allow others to view your calendar on the web, but as I am using 10.6, I am not

  • Two new replacement batteries, neither will charge

    I've gotten a new charger and two different replacement batteries for my macbook pro (early 2008). I just put in the newest one, one light on the battery turned green and then went off. The charger is orange. Battery Information:   Model Information: