Compute Date Range with SQL Statement

I'm sure there is a way to do this in SQL, but I cannot figure it out. I can write a PL/SQL script to do it, but would prefer using a SQL Statement. My database is Oracle Database 10.2.0.4.0.
I have a table that contains information such as the employee number, department id, and the effective date of when the person started in that department. There is data in another table that I want to update their department number in based on their effective date range. If I could figure out how to select the effective date range correctly, I can do the rest.
I have data such as:
EMP_ID DEPT_NO EFFECTIVE
101 1000 1/15/2001
101 1050 5/24/2005
101 2010 6/8/2008
101 1000 8/2/2010
I want to write a SELECT statement that returns something like this where the END_DATE is the day before the EFFECTIVE date and the last record does not have an END_DATE because they are still assigned to that department. Also, the first record in the column, I don't want to select a DEPT_NO because the effective date logic was added in January 2001 so if a person started back in 1985 they could have switched departments zero to many times so I'm not going to update any data for that period:
EMP_ID DEPT_NO EFFECTIVE END_DATE
101 1/14/2001
101 1000 1/15/2001 5/23/2005
101 1050 5/24/2005 6/7/2008
101 2010 6/8/2008 8/1/2010
101 1000 8/2/2010
Below is a script to create the data in a temp table that can be used to write a SELECT statement on. I have added two employee records with different dates.
create table temp_activity
(emp_id number(12),
dept_no number(12),
effective date);
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(101,1000,to_date('1/15/2001','MM/DD/YYYY'))
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(101,1050,to_date('5/24/2005','MM/DD/YYYY'))
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(101,2010,to_date('6/8/2008','MM/DD/YYYY'))
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(101,1000,to_date('8/2/2010','MM/DD/YYYY'))
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(102,1040,to_date('1/15/2001','MM/DD/YYYY'))
INSERT INTO temp_activity
(EMP_ID,DEPT_NO,EFFECTIVE)
VALUES
(102,2000,to_date('6/16/2006','MM/DD/YYYY'))
Any help is appreciated. This is probably easy, but I cannot get my brain wrapped around it.
Thanks - mike

select  emp_id,
        dept_no,
        effective,
        end_date
  from  (
          select  emp_id,
                  dept_no,
                  effective,
                  lead(effective) over(partition by emp_id order by effective) - 1 end_date,
                  row_number() over(partition by emp_id order by effective) rn
            from  temp_activity
         union all
          select  emp_id,
                  null dept_no,
                  null effective,
                  min(effective) - 1 end_date,
                  0 rn
            from  temp_activity
            group by emp_id
  order by emp_id,
           rn
    EMP_ID    DEPT_NO EFFECTIVE  END_DATE
       101                       01/14/2001
       101       1000 01/15/2001 05/23/2005
       101       1050 05/24/2005 06/07/2008
       101       2010 06/08/2008 08/01/2010
       101       1000 08/02/2010
       102                       01/14/2001
       102       1040 01/15/2001 06/15/2006
       102       2000 06/16/2006
8 rows selected.
SQL> SY.

Similar Messages

  • Date format in SQL statements

    Hi there !
    Please, can anyone help me find out what is going on with date format in my SQL Statements ?
    While in development, the date format in SQL statements were:
    SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10-DEC-2004'
    And works fine.
    After deploy to production server, we get ORACLE error: not a valid month
    So we change the format to
    SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10/12/2004'
    And it gets to works again.
    Yesterday, the net administrator updated the JAVAC / JSDK run-time with Java update tool, and AGAIN we get ORACLE error: not a valid month
    So we change the format AGAIN to
    SELECT DATA_FIELD FROM TABLE WHERE DATE_COL = '10-DEZ-2004'
    And it gets to works again.
    What is going on ?
    JAVAC running on Windows2003.
    The application access the ORACLE DB directly through JDBC.
    There is no APPLICATION SERVER, like TOMCAT.
    The regedit (windows registry) ALWAYS was and are now :
    NLS_DATE_FORMAT = DD-MON-YYYY
    NLS_LANG = AMERICAN_AMERICA.WE8ISO8859P1
    Versions:
    DB Oracle 9.2.0.5.0
    JavaC 1.4.2.05
    Thanks.
    Juliano

    Somewhere, I'm willing to wager your NLS_DATE_FORMAT was/ is being changed. This is a client-side setting. Are you sure that the setting is the same on every client machine.
    This is one of the reasons that it is considered bad form to rely on implicit conversion. If you wrap your string literal in a TO_DATE, use the JDBC escape sequence {d }, or use a Date bind variable, you don't have this problem. The bind variable approach will also play much more nicely with your database's shared pool.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Date formats for SQL statements used by recordset object

    Hi,
    Date formatting appears to be quite problematic for Business One.  I did a forum search for date issues and I don't think I saw any of them with an "answered" status.  I have an issue with formatting a date for the creation of an SQL statement that the DI sends to SQL Server 2005.  I need to format a date so that the localization parameters don't matter for either the client machine or SQL Server's machine.  We don't have a problem as long as our machines are localized as USA.
    I have PL 22 and I have a form - ours - where I use the Today() function to fill a date field.  So this is a date that is not entered by the user.  The result of this function is consistent with the localization parameters on my machine.  We have two other date fields on the form where the user must type in the date. 
    As a test, I changed my machine to the UK parameters.  I then set up the language parameters of Business One for English(United Kingdom).  I changed the date format specifications in Business One so that its format is dd/mm/yy.  I then brought up the form and the field that is formatted by the above function arrived in the form's field as dd/mm/yy.  I then typed in the two other dates in the same format and added the record to the database.  The form's table is user-defined. 
    I dismissed the form then brought it back up loaded with the new record.  The date that was entered by the function appeared in USA format (mm/dd/yy).  The dates that were typed in appeared in the Business One format (dd/mm/yy).  This of course is not consistent.
    When I looked at what got into the database, the formats were the opposite.  Weird!  To make matters really confusing, I run an SQL statement within SQL Server Mgt Studio, and use the WHERE clause to filter on the date that was based on the function.  It didn’t matter what format I used for the WHERE clause, the record came up.  Does anyone have any idea about how I can ensure that I always use the correct date format for SQL statements passed by Business One to SQL Server regardless of where in the world the application is being run?
    Thanks,
    Mike

    Ian,
    Here's what I'm concerned about:  I’m using the date in a “WHERE” clause.
    Assume the date is Aug 3, 2007.
    "SELECT * FROM Table WHERE StartDate > ‘8/3/2007’"
    OR
    "SELECT * FROM Table WHERE StartDate > ‘3/8/2007’"
    If the client machine is set up as USA, the today function will provide the date as formatted in the first query.  If the database server is setup as let’s say the UK, I believe that SQL Server query parser will interpret the date as Mar 8, 2007.
    If the client machine is set up as UK, the today function will provide the date as formatted in the second query.  If the database server is setup as let’s say USA, I believe that SQL Server query parser will also interpret the date as Mar 8, 2007.
    In both cases it would be wrong.
    I know I could use the DATEPART function to get the three parts and this will make the code indifferent to the localization specs of the client machine.  I need to then be able to concatenate those date parts for the “WHERE” clause so that the localization specifications of the database server don’t matter.
    Thanks,
    Mike

  • How do I collapse contiguous Date Ranges in SQL?

    Hi,
    In the data below, I want to collapse the contiguous date ranges with the same value (3.7) into a single date range.  I have tried and tried to come up with something but am stuck.  Does anyone know how to accomplish?
    DECLARE @Have TABLE(B DATE, E DATE, R DECIMAL(18, 1))
    INSERT INTO @Have VALUES
    ('2014-08-22', '2014-12-31', 4.0)
    , ('2015-01-01', '2015-03-29', 3.7) -- same value, contingious date ranges
    , ('2015-03-30', '2015-03-31', 3.7) -- same value, contingious date ranges
    , ('2015-04-01', '2015-09-30', 4.0)
    SELECT * FROM @Have
    DECLARE @Want TABLE(B DATE, E DATE, R DECIMAL(18, 1))
    INSERT INTO @Want VALUES
    ('2014-08-22', '2014-12-31', 4.0)
    , ('2015-01-01', '2015-03-31', 3.7) -- want to collapse into 1 date range
    , ('2015-04-01', '2015-09-30', 4.0)
    SELECT * FROM @Want
    Thanks

    Hi tballard,
    The posts from Jingyang and Cooper would be perfect only in the case that there’s no date gap between your rows. In addition to their posts, if in any case there would be a gap, please refer my code below, which works in either case.
    DECLARE @Have TABLE(B DATE, E DATE, R DECIMAL(18, 1))
    INSERT INTO @Have VALUES
    ('2014-08-22', '2014-12-30', 3.7) --same value , date gap
    , ('2015-01-01', '2015-03-29', 3.7) -- same value, contingious date ranges
    , ('2015-03-30', '2015-03-31', 3.7) -- same value, contingious date ranges
    , ('2015-04-01', '2015-09-27', 4.0) --same value, date gap
    , ('2015-10-1', '2015-12-30', 4.0) --same value, date gap
    ;WITH CTE1 AS(
    SELECT H1.B B1,H1.E E1,H1.R R1,H2.B B2,H2.E E2,ISNULL(H2.R,0) R2,ROW_NUMBER() OVER(ORDER BY H1.B) RN FROM @HAVE H1 LEFT JOIN @HAVE H2 ON DATEDIFF(DAY,H1.B,H2.E)=-1
    CTE2 AS(
    SELECT B1,E1,R1 FROM CTE1 WHERE R1 != R2
    CTE3 AS(
    SELECT B1,E1,RN,B2 FROM CTE1 WHERE R1=R2
    CTE4 AS(
    Select min(B2) B, Max(E1) E from (
    SELECT B2,E1,RN-row_number() Over(Order by B1) groupByCol
    FROM CTE3
    ) t
    Group by groupByCol
    SELECT
    C2.B1,ISNULL(C4.E,C2.E1),C2.R1
    FROM CTE2 C2 LEFT JOIN CTE4 C4 ON C2.B1=C4.B
    If you have any question, feel free to let me know.
    Best regards,
    Eric Zhang

  • Using Date objects in SQL statements

    Hi, I am wondering if it is possible to use Date objects while trying to retrieve entries from an access database with fields set as "Date/Time" fields, as opposed to "Text"? If so, do I need to reformat it before inserting it into the SQL statement, or can I just leave it as a Date object, and call up the variable name?
    For example - "SELECT * FROM database WHERE startDate = ' " + dateObject + ' ". And do i need quotes round this value?
    Thanks in advance.

    I had some problems by just fetching a date and pushing it back to a MS SQL Database.
    I used the following reformating step to fix it:
    if (o instanceof Timestamp)
    String time = o.toString().substring(8,10)+"."+o.toString().substring(5,7)+"."+o.toString().substring(0,4)+" "+o.toString().substring(11,19);
    ht.put(columnName, time);
    o is the object i receve from the select statement and ht is a Hashtable where i put my data.
    To write the data back i now can use:
    UPDATE table SET columnname = 'valueOfColumn'
    This means i use the value i created above in Quotes to write it back.
    Format of Timestamp.toString() is something like yyyy-mm-dd hh:mm:ss.xx
    Format used by MS SQL (and i think by Access to) 'dd.mm.yyyy hh:mm:ss'

  • Format Date Range in Select Statement e.b. 4/10/14 - 4/09/15

    So far thanks for all the help you've provided me on here. I'm a long time Access developer and have just worked with SQL very little throughout the years but now I'm working full-scale in it, so a learning process for me.
    I am familiar with the DateADD function in SQL DATEADD(mm, 1, GETDATE())  AS MyDate. The part that I'm struggling with is that I need to show a date range in a single field. I can not do it by having that function twice because of the character"-",
    which will throw and error. I played around with the "Convert" function some and I am thinking that a combination of the Convert and DateADD functions would be the way to accomplish this but I'm not sure.
    Basically what I need is using today's date as an example, I would need the result to return 04/10/14-04/09/15. Any assistance would be appreciated.

    This is not being used as a back-end to any type of user interface, so doing it on the front-end is not an option. The data is being exported out to text files, so it needs to be exactly as I had in the example as a single field.
    Thanks all for the feedback. Latheesh's post is the closest to what I need, in fact it's exactly what I'm looking for, which is below.
    Select Convert(varchar(20),DATEADD(mm, 1, GETDATE()),10 ) +' ---- '+ Convert(Varchar(20),DATEADD(mm, 12, GETDATE()),10)
    Ok, I got it working. Actually, turns out that it's not much different than Access syntax other than convert is used in place of Format. DateAdd, DateDiff, etc. are all used in Access as well. Thanks for all the help.

  • Strange problem with SQL-Statement

    Hi guys,
    i encountered a strange problem trying to execute a statement
    like this:
    Insert Into Data Set Text = 'Exception-Type: {0} Message: {1}';
    I'm using createStatement and executeUpdate.
    But the message stored looks like:
    Exception-Type: 0{} Message: 1{}
    I'm using MySQL 3.23. if I use ODBC everthing is o.k.!?
    Any suggestions
    Thanks

    I found a solution,
    i've thought it through once again. the sql-parsing
    mechanism seemed to be the right direction.
    i guess the odbc mysql implementation does a sql-statement
    conversion, so the string is stored correctly into the
    database. the jdbc-implementation doesn't.
    if i replace { with \{ it works. the backlash can be used
    to masquerade some characters in mysql.
    my application is database independent (or it should be)
    so i wonder if this works with oracle , db2 etc.
    mike

  • Problem with SQL Statement for Result Filtering

    Dear Visual Composer Experts,
    Here is another Question from me: I have a SQL Query that is working as the data service
    Select AB.AgingBandID, AB.AgingBand,
    Sum(Case when priority='Emergency' then '1' Else 0 End) as [Emergency],
    Sum(Case when priority='Ugent' then '1' Else 0 End) as Ugent,
    Sum(Case when priority='High' then '1' Else 0 End) as High,
    Sum(Case when priority='Medium' then '1' Else 0 End) as Medium,
    Sum(Case when priority='Low' then '1' Else 0 End) as Low
    from DimAgingBand AB left outer join
    (Select AgingBandID , priority , yeardesc
    from vNotifications where YearDesc = (select year(getdate())-1)) as vN
    on AB.AgingBandID=vN.AgingBandID
    where AB.AgingBandID<>'1'  
    Group by  AB.AgingBandID, AB.AgingBand
    Order by AB.AgingBandID
    That would return me a table as in the following:
         Agingband     E     U     H     M     L
         < 1week     0     0     0     0     1
         1 - 2 weeks     0     0     0     0     0
         2 - 4weeks     0     0     0     0     1
    > 1month     8     2     1     1     6
    Now that I would like to add some parameters to filter the result, so I modify the query and put it in the SQL Statement input port of the same data service. The query is like this:
         "Select AB.AgingBandID, AB.AgingBand,Sum(Case when priority='Emergency' then '1' Else 0 End) as [Emergency],Sum(Case when priority='Ugent' then '1' Else 0 End) as Ugent,Sum(Case when priority='High' then '1' Else 0 End) as High,Sum(Case when priority='Medium' then '1' Else 0 End) as Medium,Sum(Case when priority='Low' then '1' Else 0 End) as Low from DimAgingBand AB left outer join (Select AgingBandID , priority , yeardesc from vNotifications where YearDesc like '2009%' and Branch like '" & if(STORE@selectedBranch=='ALL', '%', STORE@selectedBranch) & "' and MainWorkCentre like '%') as vN on AB.AgingBandID=vN.AgingBandID where AB.AgingBandID<>'1' Group by AB.AgingBandID, AB.AgingBand Order by AB.AgingBandID"
    However this input port query keeps giving me error as NullPointerException. I have actually specified a condition where the query will run if only STORE@selectedBranch != u2018u2019.
    I have other filtering queries working but they are not as complicated query as this one. Could it be possible that query in the input port cannot handle left outer join?
    Could it be anything else?
    Help is very much appreciated.
    Thanks & Regard,
    Sarah

    Hi,
    Thank you very much for your replys. I've tested if the dynamic value of the condition is integer, it's OK
    But if the ClassID type is not integer, it's string, I write  a SQL Statement like:
    "Select DBADMIN.Class.ClassName from DBADMIN.Class where DBADMIN.Class.ClassID = '1' "
    or with dynamic condition:
    "Select DBADMIN.Class.ClassName from DBADMIN.Class where DBADMIN.Class.ClassID = '"&@ClassID&"'"
    or I write the SQL Statement for insert/update/delete data,
    I always have errors.
    I've tested if the dynamic value of the condition is integer, it's OK
    Do you know this problem ?
    Thank you very much & kindly regards,
    Tweety

  • Date Ranges with EOMONTH

    Hi I'm look
    for a date ranges query, any help would be greatly appreciated<o:p></o:p>
    Ie
    01/06/2014 to 30/06/2014<o:p></o:p>
    SELECT
    count(DISTINCT[Form Number]) as OutofFunding
    FROM [dbo].[NEWVIEW]
    WHERE [Cohort Desc] IN ('Apprenticeships')
    AND [Expected End] > EOMONTH(GETDATE(), -1) <o:p></o:p>

    Here is how you can do datetime range with EOMONTH:
    SELECT Count(DISTINCT[form number]) AS OutofFunding
    FROM [dbo].[newview]
    WHERE [cohort desc] IN ( 'Apprenticeships' )
    AND [expected end] > Eomonth(Getdate(), -1)
    AND [expected end] < Dateadd(dd, 1, Eomonth(Getdate(), 4));
    BLOG on datetime ranges:
    http://www.sqlusa.com/bestpractices2008/between-dates/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Date ranges with OLE DB

    Post Author: georgeb
    CA Forum: Data Connectivity and SQL
    Does anyone know if the issue with date ranges in OLE DB reports using Visual Foxpro databases has been resolved in Crystal Reports 10?
    Currently all OLE DB reports that use date ranges crash with:
    Failed to open a rowset.Details: ADO Error Code: 0x80004005Source: Microsoft OLE DB Provider for Visual FoxProDescription: SQL: Column 'DATETIME' is not foundNative Error: 806We referred this to Business Objects some time ago and their comment was that they do not supportVisual FoxPro ...
    Any assistance would be appreciated.

    Here is how you can do datetime range with EOMONTH:
    SELECT Count(DISTINCT[form number]) AS OutofFunding
    FROM [dbo].[newview]
    WHERE [cohort desc] IN ( 'Apprenticeships' )
    AND [expected end] > Eomonth(Getdate(), -1)
    AND [expected end] < Dateadd(dd, 1, Eomonth(Getdate(), 4));
    BLOG on datetime ranges:
    http://www.sqlusa.com/bestpractices2008/between-dates/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Data services with SQL Server 2008 and Invalid time format variable

    Hi all
    Recently we have switched from DI on SQL Server 2005, to DS(Date Services) on SQL Server 2008. However I have faced an odd error on the query that I was running successfully in DI.
    I validate my query output using a validation object to fill either Target table (if it passes), or the Target_Fail table (if it fails). Before sending data to the Target_Fail table, I map the columns using a query to the Target_Fail table. As I have a column called 'ETL_Load_Date' in that table, which I should fill it with a global variable called 'Load_Date'. I have set this global variable in the script at the very first beginning of the job. It is a data variable type:
    $Load_Date = to_char(sysdate(),'YYYY.MM.DD');
    When I assign this global variable to a datetime data type cloumn in my table and run the job using Data Services, I get this error:
    error message for operation <SQLExecute>: <[Microsoft][ODBC SQL Server Driver]Invalid time format>.
    However I didn't have this problem when I was running my job on the SQL Server 2005 using Data Integrator. The strange thing is that, when I debug this job, it runs completely successfully!!
    Could you please help me to fix this problem?
    Thanks for your help in advance.

    Thanks for your reply.
    The ETL_Date is a datetime column and the global variable is date data type. I have to use the to_char() function to be able to get just the date part of the current system datetime. Earlier I had tried date_part function but it returns int, which didn't work for me.
    I found what the issue was. I don't know why there were some little squares next to the name of the global variable which I had mapped to the ETL_Date in the query object!!! The format and everything was OK, as I had the same mapping in other tables that had worked successfully.
    When I deleted the column in the query object and added it again, my problem solved.

  • Problem with sql statement after migration

    Hi, recently I copied a production database X to a remote location, to serve as a test upgrade database. Original is 32 bit and test database is 64 bit. After migration it turned out that one sql statement consumed much more CPU during EXECUTE phase than on production database. Explain plans are the same. Why CPU is different? How can I trace the problem?
    ORIGINAL SERVER TKPROF OUTPUT:
    call count cpu elapsed disk query current rows
    Parse 1 0.12 0.33 0 0 2 0
    Execute 1 542.60 2165.29 2 6 0 0
    Fetch 0 0.00 0.00 0 0 0 0
    total 2 542.73 2165.62 2 6 2 0
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 66 (SPB)
    Rows     Row Source Operation
          0  SORT UNIQUE (cr=6 pr=2 pw=0 time=719909655 us)
          0   FILTER  (cr=6 pr=2 pw=0 time=719909615 us)
          2    NESTED LOOPS  (cr=0 pr=0 pw=0 time=719895787 us)
          2     HASH JOIN  (cr=0 pr=0 pw=0 time=719881575 us)
          2      NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210563833 us)
          2       NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210549798 us)
          2        NESTED LOOPS  (cr=0 pr=0 pw=0 time=1210519159 us)
    330261         REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=29176788 us)
          2         REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=1177866001 us)
          2        REMOTE  TAMPROPVALUES (cr=0 pr=0 pw=0 time=30580 us)
          2       REMOTE  TREPVALUELISTITEMS (cr=0 pr=0 pw=0 time=13973 us)
    24542745      REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=638116004 us)
          2     REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=14154 us)
          2    INDEX RANGE SCAN IDX_PROCES_ID (cr=6 pr=2 pw=0 time=13706 us)(object id 546934)
    Rows     Execution Plan
          0  INSERT STATEMENT   MODE: ALL_ROWS
          0   SORT (UNIQUE)
          0    FILTER
          2     NESTED LOOPS
          2      HASH JOIN
          2       NESTED LOOPS
          2        NESTED LOOPS
          2         NESTED LOOPS
    330261          REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "ID","STATUS","STARTDATE"
                        FROM "DIALOG6"."TWFLPROCESSINSTANCES" "PI" WHERE
                          "STATUS"<>'A' AND "STATUS"<>'N' AND "STARTDATE">=:1-30
          2          REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","ROOTCITEM_ID",
                        "PRODUCT_ID","CONTRACT_ID" FROM
                        "DIALOG6"."TAMCONTRACTEDITEMD" "CI" WHERE "PRODUCT_ID"=
                          934 AND "CONTRACT_ID"=:1
          2         REMOTE OF 'TAMPROPVALUES' (REMOTE) [T6STDBY.WR]
                       SELECT /*+ OPAQUE_TRANSFORM */ "PROPERTY_ID",
                       "VALUEOBJECT_ID","CONTRACTEDITEM_ID","DTO","ISVALID"
                       FROM "DIALOG6"."TAMPROPVALUES" "TV" WHERE "DTO" IS NULL
                       AND "ISVALID"='Y' AND "CONTRACTEDITEM_ID"=:1 AND
                         "PROPERTY_ID"=930326
          2        REMOTE OF 'TREPVALUELISTITEMS' (REMOTE) [T6STDBY.WR]
                      SELECT /*+ OPAQUE_TRANSFORM */ "ID","NAME" FROM
                        "DIALOG6"."TREPVALUELISTITEMS" "TVL" WHERE "ID"=:1
    24542745       REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE) [T6STDBY.WR]
                     SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","CONTRACT_ID" FROM
                       "DIALOG6"."TAMCONTRACTEDITEMD" "CINAD"
          2      REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE) [T6STDBY.WR]
                    SELECT /*+ OPAQUE_TRANSFORM */ "ID" FROM
                    "DIALOG6"."TWFLPROCESSINSTANCES" "SYS_ALIAS_1" WHERE "ID"=
                      :1
          2     INDEX   MODE: ANALYZED (RANGE SCAN) OF 'IDX_PROCES_ID'
                    (INDEX)
    REMOTE SERVER TKPROF OUTPUT:
    call count cpu elapsed disk query current rows
    Parse 1 0.15 0.15 0 0 2 0
    Execute      1   1210.69    3831.70          0          6          0           0
    Fetch 0 0.00 0.00 0 0 0 0
    total 2 1210.85 3831.85 0 6 2 0
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 66 (SPB)
    Rows     Row Source Operation
          0  SORT UNIQUE (cr=6 pr=0 pw=0 time=681448432 us)
          0   FILTER  (cr=6 pr=0 pw=0 time=681448397 us)
          2    NESTED LOOPS  (cr=0 pr=0 pw=0 time=681448144 us)
          2     HASH JOIN  (cr=0 pr=0 pw=0 time=681443808 us)
          2      NESTED LOOPS  (cr=0 pr=0 pw=0 time=168646003 us)
          2       NESTED LOOPS  (cr=0 pr=0 pw=0 time=168636029 us)
          2        NESTED LOOPS  (cr=0 pr=0 pw=0 time=168580989 us)
    327667         REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=9177863 us)
          2         REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=158011360 us)
          2        REMOTE  TAMPROPVALUES (cr=0 pr=0 pw=0 time=55007 us)
          2       REMOTE  TREPVALUELISTITEMS (cr=0 pr=0 pw=0 time=9947 us)
    24542745      REMOTE  TAMCONTRACTEDITEMD (cr=0 pr=0 pw=0 time=3509657414 us)
          2     REMOTE  TWFLPROCESSINSTANCES (cr=0 pr=0 pw=0 time=4309 us)
          2    INDEX RANGE SCAN IDX_PROCES_ID (cr=6 pr=0 pw=0 time=160 us)(object id 552075)
    Rows     Execution Plan
          0  INSERT STATEMENT   MODE: ALL_ROWS
          0   SORT (UNIQUE)
          0    FILTER
          2     NESTED LOOPS
          2      HASH JOIN
          2       NESTED LOOPS
          2        NESTED LOOPS
          2         NESTED LOOPS
    327667          REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "ID","STATUS","STARTDATE"
                        FROM "DIALOG6"."TWFLPROCESSINSTANCES" "PI" WHERE
                          "STATUS"<>'A' AND "STATUS"<>'N' AND "STARTDATE">=:1-30
          2          REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE)
                         [T6STDBY.WR]
                        SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","ROOTCITEM_ID",
                        "PRODUCT_ID","CONTRACT_ID" FROM
                        "DIALOG6"."TAMCONTRACTEDITEMD" "CI" WHERE "PRODUCT_ID"=
                          934 AND "CONTRACT_ID"=:1
          2         REMOTE OF 'TAMPROPVALUES' (REMOTE) [T6STDBY.WR]
                       SELECT /*+ OPAQUE_TRANSFORM */ "PROPERTY_ID",
                       "VALUEOBJECT_ID","CONTRACTEDITEM_ID","DTO","ISVALID"
                     FROM "DIALOG6"."TAMPROPVALUES" "TV" WHERE "DTO" IS NULL
                       AND "ISVALID"='Y' AND "CONTRACTEDITEM_ID"=:1 AND
                         "PROPERTY_ID"=930326
          2        REMOTE OF 'TREPVALUELISTITEMS' (REMOTE) [T6STDBY.WR]
                      SELECT /*+ OPAQUE_TRANSFORM */ "ID","NAME" FROM
                        "DIALOG6"."TREPVALUELISTITEMS" "TVL" WHERE "ID"=:1
    24542745       REMOTE OF 'TAMCONTRACTEDITEMD' (REMOTE) [T6STDBY.WR]
                     SELECT /*+ OPAQUE_TRANSFORM */ "CITEM_ID","CONTRACT_ID" FROM
                       "DIALOG6"."TAMCONTRACTEDITEMD" "CINAD"
          2      REMOTE OF 'TWFLPROCESSINSTANCES' (REMOTE) [T6STDBY.WR]
                    SELECT /*+ OPAQUE_TRANSFORM */ "ID" FROM
                    "DIALOG6"."TWFLPROCESSINSTANCES" "SYS_ALIAS_1" WHERE "ID"=
                      :1
          2     INDEX   MODE: ANALYZED (RANGE SCAN) OF 'IDX_PROCES_ID'
                    (INDEX)Edited by: Przemek P on 2012-01-27 07:40
    Edited by: Przemek P on 2012-01-27 07:50

    Could you please edit your post and use \ tags so the output is more user friendly?
    Type: \Your Code Here\It will display as:Your Code Here                                                                                                                                                                                                                                                                                                                                                                       

  • Problems with SQL statement ..Urgent Help required

    Hi
    I have a table with something like this
    ::: inidicates column seperation
    col1 ::: col2 ::: col3 ::: col4
    ab,abc,abvfg,fghy ::: x1 ::: y1 ::: z1
    ba,mkl,huji,kill ::: x2 ::: y2 ::: z2
    I want to get something like this :
    col1 ::: col2 ::: col3 ::: col4
    ab ::: x1 ::: y1 ::: z1
    abc ::: x1 ::: y1 ::: z1
    abvfg ::: x1 ::: y1 ::: z1
    fghy ::: x1 ::: y1 ::: z1
    and so on......
    Either a procedure or a single sql statement is fine..
    PS: the first column can have any number of words separated with comma (,)
    Please advise
    Thanks in advance

    create table kris (
    a varchar2(200),
    b varchar2(20),
    c varchar2(20),
    d varchar2(20));
    insert into kris values('ab,abc,abvfg,fghy', 'x1','y1','z1');
    insert into kris values('ba,mkl,huji,kill', 'x2','y2','z2');
    select substr(','||a||',', instr(','||a||',', ',', 1, rn) +1,
         instr(','||a||',', ',', 1, rn+1) - instr(','||a||',', ',', 1, rn) -1)
         v,b,c,d
    from (select length(a) - length(translate(a, '1,', '1')) +1 L,
         a, b, c, d from kris) t, (select rownum rn from cat) c
         where c.rn <= t.L
    order by a, rn;
    V B C D
    ab x1 y1 z1
    abc x1 y1 z1
    abvfg x1 y1 z1
    fghy x1 y1 z1
    ba x2 y2 z2
    mkl x2 y2 z2
    huji x2 y2 z2
    kill x2 y2 z2

  • Using bind variables with sql statements

    We connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
    When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
    Is there anybody our there with an idea of what is happening here?
    Code snippet:
    Dim OraSession As OracleInProcServer.OraSessionClass
    Dim OraDatabase As OracleInProcServer.OraDatabase
    Set OraSession = CreateObject("OracleInProcServer.XOraSession")
    Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
    OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
    OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
    OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
    Dim RS As OracleInProcServer.OraDynaset
    strSQLstatement= "Select * from my_table where igz= [my_bind] "
    Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
    OraDatabase.Parameters("my_bind").Value = myValue
    RS.Refresh
    Cheers and thanks a lot :)
    Michael Sonntag

    We connect from a VB 6.0 program via OO4O to an Oracle 8.1.7 database, using bind variables in connection with select statements. Running ok, but performance again by using bind vars not as good as expected!
    When looking into the table v$sqlarea, we were able to detect the reason. We expected that our program submits the sql statement with bind vars, Oracle parses this once, and with each select statement again, we do not have a reparse. But: It seems that with each new session Oracle reparses the sql statement, that is, Oracle is not able to memorize or cache bind vars and statements. Even more worrying, this kind of behaviour was visible with each new dynaset, but the same database/session.
    Is there anybody our there with an idea of what is happening here?
    Code snippet:
    Dim OraSession As OracleInProcServer.OraSessionClass
    Dim OraDatabase As OracleInProcServer.OraDatabase
    Set OraSession = CreateObject("OracleInProcServer.XOraSession")
    Set OraDatabase = OraSession.OpenDatabase(my database", "my connect", 0&)
    OraDatabase.Parameters.Add "my_bind", 0, ORAPARM_INPUT
    OraDatabase.Parameters("my_bind").DynasetOption = ORADYN_NOCACHE
    OraDatabase.Parameters("my_bind").serverType = ORATYPE_NUMBER ' Bind Var Type
    Dim RS As OracleInProcServer.OraDynaset
    strSQLstatement= "Select * from my_table where igz= [my_bind] "
    Set RS = OraDatabase.CreateDynaset(strSQLstatement, &H4)
    OraDatabase.Parameters("my_bind").Value = myValue
    RS.Refresh
    Cheers and thanks a lot :)
    Michael Sonntag

  • Help with sql statements and Java

    Hi,
    How can I create a string kind of like this
    Select * From Students Where Name Like "Bob Burns";
    As the sql statement might indicate I am using MS Access. I seem to be having problems with the double quotes required by the Like operator in MS Access, Java views that as a beginning of a string as oppposed to an actual string value.

    Like this:
        Connection connection = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try  {
            connection = ...get from connection pool...;
            String sql = "select ... from ... where name like ?";
            stmt = connection.prepareStatement(sql);
            stmt.setObject(1, "%Bob%", java.sql.Types.VARCHAR);
            res = stmt.executeQuery();
            while (res.next()) { ...the usual...; }
        } finally {
            ...close res, stmt & return connection to pool...
        }You can try stmt.setString() instead of setObject() but rumor has it that some mssql drivers have a bug that makes setString() not work with "like", but oddly enough setObject() works.

Maybe you are looking for

  • How can I save a file (text).....,

    ......then edit some text and save file with a new file name. Thus having both versions saved? I think the question is straight forward to anyone using lion. If not:- I write a simple text file This is a simple text file save and name as text_file_1

  • 2 Displays without using Mac Mini's thunderbolt connection?

    is it possible to connect to monitors without using the thunderbolt connection. I want to keep the thunderbolt connection for a fast external hard drive in the future. If it's not possible do you think it will be possible with the new 2013 Mini when

  • CS4: how to change cmd+H function?

    Hi, I have recently got CS4 and one thing really bugs me, the cmd+H function has changed to ctrl+cmd+H.  It used to be used to show/hide frame edges but now cmd+H appears to have been taken over by the Mac system, to hide any and all applications. I'

  • Lightroom V1.4 won't allow me to edit files converted to.dng

    I use windows vista business edition. Recently when importing raw files into Lightroom: If I leave them as raw files I can then edit them either in Lightroom or Photoshop CS3. However if I convert the files to .dng, the files are importe but when I a

  • IPhone "crashed" after 7.7 iTunes & 2.0 Software Upgrade ;-( Please HELP!!

    Ok - well I just upgraded my iTunes last night to 7.7 so that I could upgrade my iPhone software to 2.0 (fortunately I synced my iPhone prior to doing this). So after the 2.0 upgrade, my iPhone is trying to sync and then it gives me an error (Unknown