Search string-1 in string-2 gives wrong results.

Hi,
I am searching for the string 'COM' in the sentence
below.
I am getting the string positons of string "COM"
as 1 and 16.
It Should be 1 and 19.
thanks
sharath
SET SERVEROUTPUT ON
DECLARE
str VARCHAR2(200):='COM-1 Hello world COM-1 speaking';
pos NUMBER ;
ps NUMBER :=0 ;
srch VARCHAR2(20) :='COM' ;
BEGIN
While( ps <= length(str))
Loop
pos := instr(str,srch);
If pos > 0 then -- found string COM
str := substr(str,pos + length(srch));
dbms_output.put_line('COM found in pos ==> ' || pos );
End If;
ps := ps + 1;
END LOOP;
END;

I believe the problem is that you are redefining the variable str within your loop. Once you find the first occurrence of "COM" in the string, you modify the string to remove that occurrence and then search again. The logic of your stored procedure is
Loop 1:
str = "COM-1 Hello world COM-1 speaking"
- first occurrence of COM is at position 1
Loop 2:
str = "-1 Hello world COM-1 speaking"
- first occurrence of COM is at position 16 in this new string
Since you are removing the first three characters of the string when you call substr at the beginning of the second loop, you're looking for the position of "COM" in a slightly different string the second time around, hence the confusion.
If you want to find the position in the original string, you'd want something like
CREATE OR REPLACE PROCEDURE findOccurrence( string IN varchar2, search IN varchar2, offset IN number)
AS
  currentPosition NUMBER;
BEGIN
  currentPosition := INSTR( string, search );
  IF( currentPosition > 0 )
  THEN
    dbms_output.put_line( 'Search string found at position ==> ' || to_char(currentPosition+offset));
    findOccurrence( substr( string, currentPosition+length(search) ),
                    search,
                    currentPosition+length(search)+offset-1 );
  END IF;
END;
scott@jcave > exec findOccurrence( 'COM COM COM', 'COM', 0 );
Search string found at position ==> 1
Search string found at position ==> 5
Search string found at position ==> 9
PL/SQL procedure successfully completed.Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC

Similar Messages

  • Select for update gives wrong results. Is it a bug?

    Hi,
    Select for update gives wrong results. Is it a bug?
    CREATE TABLE TaxIds
    TaxId NUMBER(6) NOT NULL,
    LocationId NUMBER(3) NOT NULL,
    Status NUMBER(1)
    PARTITION BY LIST (LocationId)
    PARTITION P111 VALUES (111),
    PARTITION P222 VALUES (222),
    PARTITION P333 VALUES (333)
    ALTER TABLE TaxIds ADD ( CONSTRAINT PK_TaxIds PRIMARY KEY (TaxId));
    CREATE INDEX NI_TaxIdsStatus ON TaxIds ( NVL(Status,0) ) LOCAL;
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100101, 111, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100102, 111, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100103, 111, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100104, 111, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (200101, 222, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (200102, 222, NULL);
    Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (200103, 222, NULL);
    --Session_1 return TAXID=100101
    select TAXID from TAXIDS where LOCATIONID=111 and NVL(STATUS,0)=0 AND rownum=1 for update
    --Session_2 waits commit
    select TAXID from TAXIDS where LOCATIONID=111 and NVL(STATUS,0)=0 AND rownum=1 for update
    --Session_1
    update TAXIDS set STATUS=1 Where TaxId=100101;
    commit;
    --Session_2 return 100101 opps!?
    --Session_1 return TAXID=100102
    select TAXID, STATUS from TAXIDS where LOCATIONID=111 and NVL(STATUS,0)=0 AND rownum=1 for update
    --Session_2 waits commit
    select TAXID, STATUS from TAXIDS where LOCATIONID=111 and NVL(STATUS,0)=0 AND rownum=1 for update
    --Session_1
    update TAXIDS set STATUS=1 Where TaxId=100102;
    commit;
    --Session_2 return 100103                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    This is a bug. Got to be a bug.
    This should be nothing to do with indeterminate results from ROWNUM, and nothing to do with read consistency at the point of statement start time in session2., surely.
    Session 2 should never return 100101 once the lock from session 1 is released.
    The SELECT FOR UPDATE should restart and 100101 should not be selected as it does not meet the criteria of the select.
    A statement restart should ensure this.
    A number of demos highlight this.
    Firstly, recall the original observation in the original test case.
    Setup
    SQL> DROP TABLE taxids;
    Table dropped.
    SQL> 
    SQL> CREATE TABLE TaxIds
      2  (TaxId NUMBER(6) NOT NULL,
      3   LocationId NUMBER(3) NOT NULL,
      4   Status NUMBER(1))
      5  PARTITION BY LIST (LocationId)
      6  (PARTITION P111 VALUES (111),
      7   PARTITION P222 VALUES (222),
      8   PARTITION P333 VALUES (333));
    Table created.
    SQL>
    SQL> ALTER TABLE TaxIds ADD ( CONSTRAINT PK_TaxIds PRIMARY KEY (TaxId));
    Table altered.
    SQL>
    SQL> CREATE INDEX NI_TaxIdsStatus ON TaxIds ( NVL(Status,0) ) LOCAL;
    Index created.
    SQL>
    SQL>
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100101, 111, NULL);
    1 row created.
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100102, 111, NULL);
    1 row created.
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100103, 111, NULL);
    1 row created.
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (100104, 111, NULL);
    1 row created.
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (200101, 222, NULL);
    1 row created.
    SQL> Insert into TAXIDS (TAXID, LOCATIONID, STATUS) Values (200102, 222, NULL);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> Original observation:
    Session1>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    ROWNUM        = 1
      6  FOR UPDATE;
         TAXID
        100101
    Session1>
    --> Session 2 with same statement hangs until
    Session1>BEGIN
      2   UPDATE taxids SET status=1 WHERE taxid=100101;
      3   COMMIT;
      4  END;
      5  /
    PL/SQL procedure successfully completed.
    Session1>
    --> At which point, Session 2 returns
    Session2>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    ROWNUM        = 1
      6  FOR UPDATE;
         TAXID
        100101
    Session2>There's no way that session 2 should have returned 100101. That is the point of FOR UPDATE. It completely reintroduces the lost UPDATE scenario.
    Secondly, what happens if we drop the index.
    Let's reset the data and drop the index:
    Session1>UPDATE taxids SET status=0 where taxid=100101;
    1 row updated.
    Session1>commit;
    Commit complete.
    Session1>drop index NI_TaxIdsStatus;
    Index dropped.
    Session1>Then try again:
    Session1>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    ROWNUM        = 1
      6  FOR UPDATE;
         TAXID
        100101
    Session1>
    --> Session 2 hangs again until
    Session1>BEGIN
      2   UPDATE taxids SET status=1 WHERE taxid=100101;
      3   COMMIT;
      4  END;
      5  /
    PL/SQL procedure successfully completed.
    Session1>
    --> At which point in session 2:
    Session2>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    ROWNUM        = 1
      6  FOR UPDATE;
         TAXID
        100102
    Session2>Proves nothing, Non-deterministic ROWNUM you say.
    Then let's reset, recreate the index and explicity ask then for row 100101.
    It should give the same result as the ROWNUM query without any doubts over the ROWNUM, etc.
    If the original behaviour was correct, session 2 should also be able to get 100101:
    Session1>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    taxid         = 100101
      6  FOR UPDATE;
         TAXID
        100101
    Session1>
    --> same statement hangs in session 2 until
    Session1>BEGIN
      2   UPDATE taxids SET status=1 WHERE taxid=100101;
      3   COMMIT;
      4  END;
      5  /
    PL/SQL procedure successfully completed.
    Session1>
    --> so session 2 stops being blocked and:
    Session2>SELECT taxid
      2  FROM   taxids
      3  WHERE  locationid    = 111
      4  AND    NVL(STATUS,0) = 0
      5  AND    taxid         = 100101
      6  FOR UPDATE;
    no rows selected
    Session2>Of course, this is how it should happen, surely?
    Just to double check, let's reintroduce ROWNUM but force the order by to show it's not about read consistency at the start of the statement - restart should prevent it.
    (reset, then)
    Session1> select t.taxid
      2   from
      3    (select taxid, rowid rd
      4      from   taxids
      5      where  locationid = 111
      6      and    nvl(status,0) = 0
      7      order by taxid) x
      8   ,  taxids t
      9   where t.rowid = x.rd
    10   and   rownum = 1
    11   for update of t.status;
         TAXID
        100101
    Session1>
    --> Yes, session 2 hangs until...
    Session1>BEGIN
      2   UPDATE taxids SET status=1 WHERE taxid=100101;
      3   COMMIT;
      4  END;
      5  /
    PL/SQL procedure successfully completed.
    Session1>
    --> and then
    Session2> select t.taxid
      2   from
      3    (select taxid, rowid rd
      4      from   taxids
      5      where  locationid = 111
      6      and    nvl(status,0) = 0
      7      order by taxid) x
      8   ,  taxids t
      9   where t.rowid = x.rd
    10   and   rownum = 1
    11   for update of t.status;
         TAXID
        100102
    Session2>Session 2 should never be allowed to get 100101 once the lock is released.
    This is a bug.
    The worrying thing is that I can reproduce in 9.2.0.8 and 11.2.0.2.

  • 0CRM_OPPT_H  (Transaction RSA3 gives wrong result)

    Hi gurus,
    <b>0CRM_OPPT_H  (Transaction RSA3 gives wrong result)
    BBPCRM 4.0
    BW 3.50 version</b>
    I had enhanced the structure "crmt_bw_oppt_h"
    and also written a BADI to populate Opportunity header status.
    But when I run extract checker RSA3 for CRM data,
    I get wrong number of records.
    I am having 95 records for Opportunities header data.
    Data Records / Call = "100"
    Display Extr. Calls = "10"
    Above settings, I am retrieving only 61 records.
    <b>Data Records / Call = "1"
    Display Extr. Calls = "200"
    For the above settings in RSA3,
    I am able to retrieve 95 records correctly.</b>
    The problem is that in RSA1 transaction of BW 3.50 server also,
    61 records are being loaded from CRM server.
    <b>Could this be a Cache memory problem,
    Are any of my BASIS settings a cause for this problem?</b>
    Any help is really appreciated and will be rewarded.
    Thanks,
    Aby Jacob
    ========

    Dear Friends,
    <b>I had to do a small correction in my BADI code.
    I got a solution from Online SAP HELP portal.</b>
    http://help.sap.com/saphelp_nw04/helpdata/en/eb/3e7cf4940e11d295df0000e82de14a/frameset.htm
    Notes on BADI Usage
    ====================
    The instance generated through the factory method should be declared
    as globally as possible or generally be passed as a parameter
    to ensure that the initialization process must be run as rarely as possible
    – just once would be best. In no case should you discard the instance as soon as
    it is generated or repeatedly run the initialization process in a loop.
    Within the adapter class interface,
    required database accesses are buffered locally,
    so that each access is executed once only.
    However, repeated initialization makes
    the buffer useless and dramatically reduces performance.
    Due to the local buffering, you can call Business-Add-In methods
    without having to expect considerable performance restrictions,
    even if no active implementations exist.
    Also, if the definition of the Business-Add-In is filter-dependent,
    a single instance is sufficient.
    However, you should not do without initialization altogether.
    Even if you could call static methods of the implementing
    class of the Business-Add-In implementation without an instance,
    you would lose the benefit of performance improvement through
    the Business-Add-Ins and the possibility of multiple use.
    If you switch the method type in the interface from the static method
    to the instance method at any time in the future,
    many code adjustments are required.
    In addition, you can no longer use default code that is provided.
    <b>Many Thanks to ROBIN
    and the whole SDN team</b>
    Aby Jacob ,,,,,

  • ITSM Search on status with "is not" gives incorrect results due to SLA statuses

    Hi,
    When executing a search on Solution Manager ITSM tickets, on the search criterion Status and with operator "is not", the result list does not give correct results.
    For example, an incident with status "Confirmed IRT Exceeded" does show up when searching with criterion "Status is not Confirmed".
    Is there any solution for this behaviour?
    Kind Regards,
    Joyca

    Hi Vivek,
    Thanks for the Knowledge Article.
    The content of the document would indeed help if we only wanted to find "not confirmed" tickets.
    However, the same thing is happening on other statuses. For example searching for "status is not proposed solution" is still not possible with the descriptions in the knowledge document, since the user status "proposed solution" is linked to system status "in process" (I1003), like all the other in-between user statuses such as "customer action" and "in process" etc.
    The only workaround that I see is to use only "is" as operator and never "is not". However, the underlying problem remains. I think it should be possible to use also "is not" without having issues due to those SLA statuses...
    Kr,
    Joyca

  • GetFloatProperty gives wrong result for values out of range

    Hi
    When the method setFloatProperty is called by setting the float values out of the range,then calling getFloatProperty does not give NumberFormatException.
    Float value set more the MAX_VALUE of float returns infinity when getFloatProperty is called.Similar problem occurs with setDoubleProperty.This behavior is confusing.can anyone help me out.
    Regards
    saroj13

    Throwing a NumberFormatException would never make sense in this situation. The exception indicates that you are trying to convert a String to a number, but the String does not contain a valid number. eg. "as3"; when a conversion was attemted would throw a NumberFormatException.
    Floats and Doubles in Java comply with the IEEE 754 standard which mandates the behaviour of the types.
    Could you explain why you find this confusing?
    Hope this helps.

  • Count function on months column gives wrong result

    Hi,
    I am on OBIEE 11.1.1.7.150120.
    I used the count function on the month column and rather than getting 12 as the answer i get 365. (i used a filter on the year column to restrict it to one year)
    How could this happen?
    Any help would be appreciated.

    I was able to get the answer as 12 on the month column in the Dim_Time using the count distinct.
    The main reason i was trying this is because i have a VALUE column in VIew_A. I am trying to sum the values of these, but when i use the sum function, the output is quite huge and wrong. I dosen't match with the monthly figures.
    For eg:
    Month
    Income Cost
    JAN
    186.96
    FEB
    309.29
    MAR
    246.82
    APR
    247.95
    998.76
    1,462.74
    MAY
    160.27
    645.60
    1,643.84
    JUN
    172.19
    693.61
    927.12
    JUL
    150.27
    605.32
    855.89
    AUG
    133.61
    483.66
    538.20
    789.22
    SEP
    144.56
    412.42
    582.34
    824.84
    OCT
    264.96
    315.66
    364.00
    631.32
    1,067.32
    1,466.22
    NOV
    240.39
    832.10
    968.32
    1,058.73
    1,638.38
    DEC
    215.81
    857.30
    869.31
    24005.34
    But if i use the sum function on the Income/cost column, the value i get is
    C_MONTH
    SUM(INCOME_COST)
    JAN
    5,795.86
    FEB
    8,660.21
    MAR
    7,651.52
    APR
    81,283.62
    MAY
    75,941.13
    JUN
    53,787.67
    JUL
    49,955.96
    AUG
    60,285.39
    SEP
    58,924.80
    OCT
    127,394.01
    NOV
    142,137.76
    DEC
    60,215.18
    This just doesn't work out. I need the answer to be 24005 by using the sum function

  • Bug in 10.2.0.3.0 - sum gives wrong result?

    Hi,
    I've found a strange behavior when using sum without group by. Firs I thought it's hash group by, but it's supposed to be fixed in 10.2.0.3, and setting GBYHASH_AGGREGATION_ENABLED=FALSE also didn't fix the error.
    We have automated tests to verify our results of views and procedures. The test works on a small subset of data, so it uses the following (pseudo) select to calcuate the expected value:
    select
    sum(round(trw.a* rc.b,2))
    into
    tmp_result
    from
    trw
    inner join rc on rc.cp_id= trw.cp_id and rc.r_id= trw.r_id and rc.pc_id=param_pc_id
    where
    trw.t_id= test_t_id;
    Now, this select returns a value that's a little bit different than a value we get from the view we are testing.
    The view is basically the same, it has a group by trw.t_id and some simple logic.
    The interesting part is this:
    if I dump "un-summarized" data from the view and the select statement into temporary tables, i get the same rows, and sum over those rows gives the right value.
    Either I've missed something obvious or it truly is a bug. Any ideas?
    Regards
    Jernej

    OMG, my bad, I'm sorry.
    That's what happens when you test sysdate dependent results.
    Sorry again

  • Week function gives wrong result for last week in year

    Week(CreateDate(2011,12,25)) returns 51 - correct
    Week(CreateDate(2011,12,26)) returns 53 - wrong
    It looks like all last weeks of the year are 53 whereas the next year with 53 weeks should be 2015.
    See http://tuxgraphics.org/toolbox/calendar.html for example.
    I am running CF9 on Windows 7 with Java V6 update 29.
    This is causing me a problem. Any ideas for a workaround?
    Doug

    Here is my general solution for my cfc which seems to work for all dates up to 2100 at least.
    Hope it can help if you need a Week function to replace the CF one.
    <cffunction name="getISOWeekNum" access="public" returntype="Numeric" hint="Gets ISO week number in which date occurs.">
        <cfargument name="date" type="date" required="true" hint="Date for which you wish to know the week number">
        <cfset var weeknum = 0>
        <cfset var isLeap = isLeapYear(Year(date))>
        <cfset var dayInWeek = dayOfWeek(date)>
        <cfset var isoDayOfWeek = iIf(dayInWeek GT 1, dayInWeek - 1, 7)>
        <cfset var nearestThur = dateAdd("d", 4 - isoDayOfWeek, date)>
        <cfset var fourthDayOfYear = createDate(year(nearestThur), 1, 4)>
        <cfset var fourthDayInWeek = dayOfWeek(fourthDayOfYear)>
        <cfset var fourthIsoDayOfWeek = iif(fourthDayInWeek GT 1, fourthDayInWeek - 1, 7)>
        <cfset var firstThur = dateAdd("d", 4 - fourthIsoDayOfWeek, fourthDayOfYear)>
        <cfset var lastWeek = iIf(fourthDayInWeek EQ 8 OR (isLeap AND fourthDayInWeek EQ 7), 53, 52)>
        <cfset var firstIsoDayOfFirstWeek = dateAdd("d", -(fourthIsoDayOfWeek-1), fourthDayOfYear)>
        <cfset var firstIsoDayOfLastWeek = dateAdd("d", -7, firstIsoDayOfFirstWeek)>
        <cfset var lastIsoDayOfFirstWeek = dateAdd("d", 6, firstIsoDayOfFirstWeek)>
        <cfset var weekDiff = iIf(dateCompare(date, firstIsoDayOfFirstWeek, "d") EQ -1, 0, 1)>
        <cfif dateCompare(date, firstIsoDayOfFirstWeek, "d") EQ -1 AND dateCompare(date, firstIsoDayOfLastWeek, "d") NEQ -1>
            <cfset weeknum = lastWeek>
        <cfelseif dateCompare(date, lastIsoDayOfFirstWeek, "d") NEQ 1 AND dateCompare(date, firstIsoDayOfLastWeek, "d") NEQ -1>
            <cfset weeknum = 1>
        <cfelse>
            <cfset weeknum = weekDiff + (dateDiff("d", firstThur, nearestThur) / 7)>
        </cfif>
        <cfreturn weeknum>
    </cffunction>
    Doug

  • SPField.Hidden gives wrong result

    This code returns fields that are hidden in the list settings page. Why is that?
    var fields = from SPField field in list.Fields
    where field.Type == SPFieldType.User && !field.Hidden
    select field;

    Yes I had the setting for 'Update all content types inheriting from this type? ' set to yes in the content type advanced settings. As I stated in the post above where I came
    up with a solution: using the list.ContentTypes and then the contenttype.fields to loop through the fields the Contact field there is actually hidden. But looping through the list.Fields the Contact field is not hidden. So yes my Content Type did get pushed
    down from the site content type to each of the pages libraries in each of my sub webs. But NO it does not also affect the field in list object. This can be seen both when debugging my code and also simply by using SharePoint Manager 2013.
    In SP Manager if I go to Sites\mysite\allwebs\subweb\lists\pages\fields
    then click the Contact item, Hidden = False
    If I go to Sites\mysite\allwebs\subweb\lists\pages\ContentTypes\MyContentType\fields
    then click the Contact item, Hidden = True
    The solution appears to be to use the list.ContentTypes to get the field rather than list.fields. This works the way I want.

  • Query gives wrong result

    Hello
    I need to derive result as mentioned below. In case of time range overlap, minimum of start time and maximum of end time should retrived.
    day               start_time     end_time
    sun               6:00                    6:15
    sun               6:30                    6:45
    sun               6:45                    7:00
    sun               7:00                    7:15
    mon               6:00                    6:15
    mon               7:00                    8:00
    o/p
    day          start_time     end_time
    sun          6:00                         6:15
    sun          6:30                         7:15
    mon          6:00                         6:15
    mon          7:00                         8:00
    We have tried with below query
    SELECT DISTINCT ctry_code emp_nbr, day, start_time,
                    end_time,               
                    (case when end_time = (LEAD (start_time) OVER (PARTITION BY ctry_code, emp_nbr, day ORDER BY ctry_code,
                             emp_nbr,
                             day,
                             start_time
                             )) then
                             'N'                      
                            else
                            'Y'
                     end) take_not               
               FROM sales_man
              WHERE emp_nbr = 230
           ORDER BY day, start_time
    From above query we have found below result which is incorrect.
    day          start_time            end_time
    sun          6:00          6:30
    sun          6:45          7:00
    sun          7:00          7:15
    mon          6:00          6:15
    mon          7:00          8:00Please help on this
    Thanks in advance

    Like this perhaps?
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'sun' as day, '6:00' as start_time, '6:15' as end_time from dual union all
      2             select 'sun', '6:30', '6:45' from dual union all
      3             select 'sun', '6:45', '7:00' from dual union all
      4             select 'sun', '7:00', '7:15' from dual union all
      5             select 'mon', '6:00', '6:15' from dual union all
      6             select 'mon', '7:00', '8:00' from dual)
      7  --
      8  -- end of test data
      9  --
    10  select day
    11        ,max(decode(tm,1,time)) as start_time
    12        ,max(decode(tm,2,time)) as end_time
    13  from (
    14        select day, time
    15              ,round((row_number() over (partition by day order by to_date(lpad(time,5,'0'),'hh24:mi'))+0.5)/2) as rn
    16              ,2-mod(row_number() over (partition by day order by to_date(lpad(time,5,'0'),'hh24:mi')),2) as tm
    17        from (
    18                    select day, decode(rn,1,start_time,end_time) as time
    19              from t cross join (select rownum rn from dual connect by rownum <= 2)
    20              group by day, decode(rn,1,start_time,end_time)
    21              having count(*) = 1
    22             )
    23       )
    24  group by day, rn
    25* order by day, rn
    SQL> /
    DAY STAR END_
    mon 6:00 6:15
    mon 7:00 8:00
    sun 6:00 6:15
    sun 6:30 7:15
    SQL>Obviously the ordering of the days in the result is based on the alphabetic name so "mon" comes before "sun", but you could change that easy enough like this...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'sun' as day, '6:00' as start_time, '6:15' as end_time from dual union all
      2             select 'sun', '6:30', '6:45' from dual union all
      3             select 'sun', '6:45', '7:00' from dual union all
      4             select 'sun', '7:00', '7:15' from dual union all
      5             select 'mon', '6:00', '6:15' from dual union all
      6             select 'mon', '7:00', '8:00' from dual)
      7  --
      8  -- end of test data
      9  --
    10  select day
    11        ,max(decode(tm,1,time)) as start_time
    12        ,max(decode(tm,2,time)) as end_time
    13  from (
    14        select day, time
    15              ,round((row_number() over (partition by day order by to_date(lpad(time,5,'0'),'hh24:mi'))+0.5)/2) as rn
    16              ,2-mod(row_number() over (partition by day order by to_date(lpad(time,5,'0'),'hh24:mi')),2) as tm
    17        from (
    18                    select day, decode(rn,1,start_time,end_time) as time
    19              from t cross join (select rownum rn from dual connect by rownum <= 2)
    20              group by day, decode(rn,1,start_time,end_time)
    21              having count(*) = 1
    22             )
    23       )
    24  group by day, rn
    25  order by decode(day,'sun',1,'mon',2,'tue',3,'wed',4,'thu',5,'fri',6,'sat',7)
    26*      ,rn
    SQL> /
    DAY STAR END_
    sun 6:00 6:15
    sun 6:30 7:15
    mon 6:00 6:15
    mon 7:00 8:00

  • Function gives wrong results

    I've calculated it myself and get different results.
    FUNCTION calc_customer_profit (p_custid in number)
    RETURN NUMBER
    IS
    v_days number default 0;
    v_profit number default 0;
    cursor c_profitvalues is
         select ren.customer_id
         ,               ren.rent_dt
         ,               ren.return_dt
         ,               ren.daily_rate
         from rentals ren
         where ren.customer_id = p_custid
         order by ren.customer_id;
    BEGIN
         for r_profitvalues in c_profitvalues loop
              v_days := Days_Between(r_profitvalues.rent_dt, r_profitvalues.return_dt);
              v_profit := (v_days*r_profitvalues.daily_rate)+v_profit;
         end loop;
         return v_profit;
    END calc_customer_profit;

    How about this:
    SQL> create or replace
      2  FUNCTION Days_Between (first_dt IN DATE, second_dt IN DATE := sysdate) RETURN NUMBER
      3  IS
      4  BEGIN
      5    RETURN TO_NUMBER(TO_CHAR(second_dt, 'J')) - TO_NUMBER(TO_CHAR(first_dt , 'J'));
      6  END;
      7  /
    Function created.
    SQL>
    SQL> set null {null}
    SQL>
    SQL> select dt1, dt2, Days_Between(dt1, dt2)
      2  from (
      3  select to_date('24.12.2004', 'DD.MM.YYYY') dt1, to_date('01.01.2005', 'DD.MM.YYYY') dt2 from dual
      4  union all
      5  select to_date('01.01.2005', 'DD.MM.YYYY') dt1, to_date('08.01.2005', 'DD.MM.YYYY') dt2 from dual
      6  union all
      7  select to_date('01.01.2005', 'DD.MM.YYYY') dt1, to_date('01.01.2005', 'DD.MM.YYYY') dt2 from dual
      8  union all
      9  select to_date(NULL, 'DD.MM.YYYY') dt1, to_date('01.01.2005', 'DD.MM.YYYY') dt2 from dual
    10  union all
    11  select to_date('01.01.2005', 'DD.MM.YYYY') dt1, to_date(NULL, 'DD.MM.YYYY') dt2 from dual
    12  );
    DT1       DT2       DAYS_BETWEEN(DT1,DT2)
    24-DEC-04 01-JAN-05                     8
    01-JAN-05 08-JAN-05                     7
    01-JAN-05 01-JAN-05                     0
    {null}    01-JAN-05 {null}
    01-JAN-05 {null}    {null}
    SQL>

  • Bug: "=" does give wrong result!

    hi, this is the most frightening oracle bug I saw. 10gr2, data imported from an 9 export:
    select count(*) from T where F = 1;
    0select count(*) from T where F between 1 and ;
    1165select count(*) from T where nvl(F, 1) = 1;
    1165select count(*) from T where F <= 1;
    1165select count(*) from T where F < 1;
    0in one word: HELP !
    ps: no index on F, stats computed...

    it is a bug actually, because an execution plan should not affect the result of the query ! Report it to metalink if you do have a valid support contract
    SQL> select count(*) from t where f = 1
    Execution Plan
    Plan hash value: 600826401
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |     1 |    13 |     0   (0)|          |
    |   1 |  SORT AGGREGATE     |      |     1 |    13 |            |          |
    |*  2 |   FILTER            |      |       |       |            |          |
    |*  3 |    TABLE ACCESS FULL| T    |     1 |    13 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter(NULL IS NOT NULL)
       3 - filter("F"=1)
    Note
       - dynamic sampling used for this statement
    SQL> select count(*) from t where f between 1 and 1;
    Execution Plan
    Plan hash value: 1842905362
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |     1 |    13 |     2   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE    |      |     1 |    13 |            |          |
    |*  2 |   TABLE ACCESS FULL| T    |     1 |    13 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter("F"=1)
    Note
       - dynamic sampling used for this statement

  • Please Help Urgent:Fast Search returning wrong result sets

    Hi All,
    We are facing below issue with fast search.
    Currently in My project  when  we are searching  for a phrase it is returning wrong result sets.
    For example if we search for “Endura”, It is returning documents related to
    Endura  as well as Centura.
    But the expected results are only Endura documents.
    When we look in to the documents we didn’t find the search term (“Endura” ) either inside document content or in its meta data.
    In order to resolve the issue we tried the below steps
    1-     
    We manually edited and saved the document, to ensure the appropriate Guid association to metadata.
    2-     
    Index reset
    3-     
    Full crawl
    But no luck  so far.
    Please help.Thanks in advance.
    Regards
    Subrat

    Subrat,
    This may be related to spellchecking or may be synonym. Spellcheck is based on indexed terms.
    The best test would be to run the queries from qrserver (13280) and then look at the spellcheck query transformations. If spellchecking is not doing it, then you must have a synonym setup .Check your keyword/synonyms from the SharePoint side. 

  • SQL Server 2012 Time(7) DataType values Comparison giving wrong result. Please help

    We have a Table with StartTime and EndTime columns in Time(7) datatype, so we want to count the rows for each hour from 6 AM to 5 AM. If a record in table is as StartTime= 7 PM to EndTime = 5 AM (a shift of an employee) then the result is wrong beacause
    being time(7) datatype the EndTime(5AM)< StartTime(7PM) in 24 hours format so following query gives wrong results.
    select
    * from EmpSchedule
    where (StartTime>='19:00:00.0000000'
    OR EndTime>='19:00:00.0000000')
    Please help me out. Thanks

    DECLARE @clockIns TABLE (employeeID INT, startDateTime DATETIME, endDateTime DATETIME)
    INSERT INTO @clockIns (employeeID, startDateTime, endDateTime)
    VALUES
    (1, '2014-07-01 19:01:00.000', '2014-07-02 04:27:00.000'),
    (2, '2014-07-01 18:01:00.000', '2014-07-02 05:27:00.000'),
    (3, '2014-07-01 19:01:00.000', '2014-07-02 05:27:00.000'),
    (4, '2014-07-01 18:01:00.000', '2014-07-02 04:27:00.000')
    SELECT *
    FROM @clockIns
    WHERE datepart(HOUR,startDateTime) BETWEEN 19 AND 23
    OR datepart(HOUR,startDateTime) BETWEEN 0 AND 4
    OR datepart(HOUR,endDateTime) BETWEEN 19 AND 23
    OR datepart(HOUR,endDateTime) BETWEEN 0 AND 4
    Try this out.

  • How to search for a pattern string in entire registry and delete all the keys and subkeys that contain the pattern (C# or VB)?

    I want to search for a pattern string in the entire registry and need to delete all the keys and sub-keys that contain the pattern. How can I implement this in VB Script or C#? Appreciate if you can give some sample examples. Now every time, I am manually
    searching for the pattern in registry and deleting one by one.
    Thanks Prasad

    There is no built in way to do this. You'll end up having to enumerate all keys and values in the entire registry and comparing each one for a pattern using Regex or similar.  This is going to be really slow but there isn't much else you can do about
    it (other than parallelize the enumeration).  Also note that you won't have permissions to all keys for read and/or write access so you'll need to skip over those using exception handling.
    Michael Taylor
    http://blogs.msmvps.com/p3net

Maybe you are looking for

  • Trying to insert flash video onto website

    I'm using Dreamweaver and have been trying to embed a flash video onto my web page. I have inserted the proper file, but I think I need to reference the start.exe file to get the movie to play. Any help? This is the code so far: <object classid="clsi

  • Conversion from Direct to Flexible Update

    Dear Gurus, Currently we have direct update for InfoObject 0CUST_SALES (DELTA LOAD). We have to write some update rules for 0CUST_SALES_ATTR and hence we have to go for Flexible Update. However I do not know any way by which we can just change the ty

  • Can I load windows office into iPad?

    Hi, I am looking at buying my partner the iPad or iPad2 and was wondering if Windows Office for Mac can be loaded into it?

  • "Macro" function like in Word?

    I cannot find the macro function (or whatever its called in Pages). I want to have a set of text, such as a return address, that I can call into a Pages document. Where does it live? Or what is it called so I can look it up in the manual? Thanks

  • Adding constraint to table

    Hi, I'm hoping that this will fall under this discussin forum. Recently we've been having problems with some customers having the same email addresses assigned to them. I checked the table and currently there are no constraints on this column (EMAIL_