SQL Query to calculate on-time dispatch with a calendar table

Hi Guys,
I have a query (view) to calculate orders' fulfillment leadtimes.
The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
Please find below the current calculation for the On-Time Column:
SELECT
Week#
, ClntGroup
, CORD_DocumentCode
, DESP_DocumentCode
, Cord_Lines --#lines ordered
, CORD_Qty --total units orderd
, DESP_Lines --#lines dispatched
, DESP_Qty --total units dispatched
, Status
, d_status
, OpenDate --order open date
, DateDue
, DESP_PostedDate --order dispatched date
, DocType
, [Lead times1]
, [Lead times2]
, InFxO
, OnTime
, InFxO + OnTime AS InFullAndOneTime
, SLADue
FROM (
SELECT
DATEPART(WEEK, d.DateOpn) AS Week#
, Clients.CustCateg
, Clients.ClntGroup
, d.DocumentCode AS CORD_DocumentCode
, CDSPDocs.DocumentCode AS DESP_DocumentCode
, COUNT(CORDLines.Qnty) AS Cord_Lines
, SUM(CORDLines.Qnty) AS CORD_Qty
, COUNT(CDSPLines.Qnty) AS DESP_Lines
, SUM(CDSPLines.Qnty) AS DESP_Qty
, CDSPLines.Status
, d.Status AS d_status
, d.OpenDate
, d.DateDue
, CDSPDocs.PostDate AS DESP_PostedDate
, d.DocType
, DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
, DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
, CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
--On-Time by order according to Despatch SLAs
, CASE
WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
THEN 1
WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
THEN 1
WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
AND d.DateDue >= CDSPDocs.PostDate
THEN 1
ELSE 0
END AS OnTime
--SLA Due (as a control)
, CASE
WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
THEN DATEADD(DAY, 2 , d.OpenDate)
WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
AND CDSPDocs.PostDate IS NULL
THEN DATEADD (DAY, 14 , d.OpenDate)
ELSE CDSPDocs.PostDate
END AS SLADue
FROM dbo.Documents AS d
INNER JOIN dbo.Clients
ON d.ObjectID = dbo.Clients.ClntID
AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
ON d.DocID = CORDLines.DocID
AND CORDLines.TrnType = 'L'
LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
ON CORDLines.TranID = CDSPLines.SourceID
AND CDSPLines.TrnType = 'L'
AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
LEFT OUTER JOIN dbo.Documents AS CDSPDocs
ON CDSPLines.DocID = CDSPDocs.DocID
LEFT OUTER JOIN DimDate
ON dimdate.[Date] = d.OpenDate
WHERE
d.DocType IN ('CASW', 'CORD', 'MORD')
AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
AND CORDLines.LneType IS NOT NULL
AND d.DateDue <= CONVERT(date, GETDATE(), 101)
GROUP BY
d.DateOpn
,d.DocumentCode
,Clients.CustCateg
,CDSPDocs.DocumentCode
,d.Status
,d.DocType
,d.OpenDate
,d.DateReq
,CDSPDocs.PostDate
,CDSPLines.Status
,Clients.ClntGroup
,d.DocumentName
,d.DateDue
,d.DateOpn
) AS derived_table
Please find below the DimDate table
FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
24/12/2014 NULL 0 1
25/12/2014 Christmas Day 1 0
26/12/2014 Boxing Day 1 0
27/12/2014 NULL 0 0
28/12/2014 NULL 0 0
29/12/2014 NULL 0 1
30/12/2014 NULL 0 1
31/12/2014 NULL 0 1
1/01/2015 New Year's Day 1 0
2/01/2015 Day after New Year's 1 0
3/01/2015 NULL 0 0
4/01/2015 NULL 0 0
5/01/2015 NULL 0 1
6/01/2015 NULL 0 1
This is what I get from the query:
Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
52 Web Sales 123456 24/12/2014 29/12/2014 0
52 Web Sales 123457 24/12/2014 30/12/2014 0
52 Web Sales 123458 24/12/2014 29/12/2014 0
52 Local Market 123459 24/12/2014 29/12/2014 0
1 Web Sale 123460 31/12/2014 5/01/2015 0
1 Local Market 123461 31/12/2014 6/01/2015 0
As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
52 Web Sales 123456 24/12/2014 29/12/2014 1
52 Web Sales 123457 24/12/2014 30/12/2014 1
52 Web Sales 123458 24/12/2014 29/12/2014 1
52 Local Market 123459 24/12/2014 29/12/2014 1
1 Web Sale 123460 31/12/2014 5/01/2015 1
1 Local Market 123461 31/12/2014 6/01/2015 1
I am using SQL Server 2012
Thanks
Eric

>> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
CREATE TABLE Calendar
(cal__date date NOT NULL PRIMARY KEY, 
 julian_business_nbr INTEGER NOT NULL, 
INSERT INTO Calendar 
VALUES ('2007-04-05', 42), 
 ('2007-04-06', 43), -- good Friday 
 ('2007-04-07', 43), 
 ('2007-04-08', 43), -- Easter Sunday 
 ('2007-04-09', 44), 
 ('2007-04-10', 45); --Tuesday
To compute the business days from Thursday of this week to next
 Tuesdays:
SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
 FROM Calendar AS C1, Calendar AS C2
 WHERE C1.cal__date = '2007-04-05',
 AND C2.cal__date = '2007-04-10'; 
We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
look stupid in 2015. 
You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
And you need to read and download the PDF for: 
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> Please find below the current calculation for the On-Time Column: <<
“No matter how far you have gone down the wrong road, turn around”
 -- Turkish proverb
Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
ONE statement than I have seen in entire major corporation databases.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Sql query to calculate total credit having more than one tables

    i have these 9 tables and want to calculate totalcredit from these tables alse want to
    See more: SQL-server-2008R2
    i have these 9 tables and want to calculate totalcredit from these tables alse want to calculate totaldebit of all account no in which each accountno will show its own total credit and total debit 
    parties
    purchase 
    purchase body
    purchase return
    purchase return body
    sale 
    sale body
    sale return
    sale return body

    If you want to suggest you accurate solution, please post CREATE TABLE+ INSERT INTO + sample data + DESIRED RESULT
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Need  the query to calculate the time taken to excute it.

    hi all,
    i need the query to calculate the time taken to excute it.
    for ex:
    select * from emp;
    how much time it will take to give o/p
    Thanks in advance
    satya

    Just to add to what was said - the execution can each time be DIFFERENT as the factors that governs performance are NOT CONSTANT.
    If Oracle has no idea how long the query is going to take before executing it, then how can you and your code know?
    Oracle's CBO estimates the cost (expense) of the query. This is an indication of how expensive a query is - and the more expensive the query, the more resources need to be used, the longer the query will take. The less expensive the query, the fewer resources it need, the faster it will take.
    And that is it. How fast or how slow? Oracle does not know. How much faster a query with a cost of 10,000 versus a query with a cost of 1? Oracle does not know.
    Why? Because the platform is not constant. Just what data is at this exact moment in the db buffer cache? Just how much CPU capacity is available for the new few seconds? Just what will the sustained throughput be of the I/O subsystem and channels for the next minute? Just how many memory pages need to be swapped between cache and memory? Etc. etc.
    All these factors change every single second. So forget about attempting to accurately calculate up-front the time it will take for a query. IT IS NOT POSSIBLE.

  • How to write a SQL query in SAP B1 2007 B with input parameters?

    How to write a SQL query in SAP B1 2007 B with input parameters, on execution of which will ask for some input value from the user and the values will be selected from a list such as item list?

    The syntax like
    SELECT * FROM OITM T0 WHERE T0.ItemCode = '[%0\]'
    Thanks,
    Gordon

  • Sql Query taking very long time to complete

    Hi All,
    DB:oracle 9i R2
    OS:sun solaris 8
    Below is the Sql Query taking very long time to complete
    Could any one help me out regarding this.
    SELECT MAX (md1.ID) ID, md1.request_id, md1.jlpp_transaction_id,
    md1.transaction_version
    FROM transaction_data_arc md1
    WHERE md1.transaction_name = :b2
    AND md1.transaction_type = 'REQUEST'
    AND md1.message_type_code = :b1
    AND NOT EXISTS (
    SELECT NULL
    FROM transaction_data_arc tdar2
    WHERE tdar2.request_id = md1.request_id
    AND tdar2.jlpp_transaction_id != md1.jlpp_transaction_id
    AND tdar2.ID > md1.ID)
    GROUP BY md1.request_id,
    md1.jlpp_transaction_id,
    md1.transaction_version
    Any alternate query to get the same results?
    kindly let me know if any one knows.
    regards,
    kk.
    Edited by: kk001 on Apr 27, 2011 11:23 AM

    Dear
    /* Formatted on 2011/04/27 08:32 (Formatter Plus v4.8.8) */
    SELECT   MAX (md1.ID) ID, md1.request_id, md1.jlpp_transaction_id,
             md1.transaction_version
        FROM transaction_data_arc md1
       WHERE md1.transaction_name = :b2
         AND md1.transaction_type = 'REQUEST'
         AND md1.message_type_code = :b1
         AND NOT EXISTS (
                SELECT NULL
                  FROM transaction_data_arc tdar2
                 WHERE tdar2.request_id = md1.request_id
                   AND tdar2.jlpp_transaction_id != md1.jlpp_transaction_id
                   AND tdar2.ID > md1.ID)
    GROUP BY md1.request_id
            ,md1.jlpp_transaction_id
            ,md1.transaction_versionCould you please post here :
    (a) the available indexes on transaction_data_arc table
    (b) the description of transaction_data_arc table
    (c) and the formatted explain plan you will get after executing the query and issuing:
    select * from table (dbms_xplan.display_cursor);Hope this helps
    Mohamed Houri

  • SQL query runs too many times in SQL server Profiler

    Hi Experts
    I have designed a report using SQL database.Report is based on Add Command Object, View and Table.Which are link and gives desired output.
    However it takes long time. In the SQL Sever profiler it shows that query is executing too many times.
    When in the Add Command object I edit the query Say I write TOP 5000 then it executes once however if I write Add 5001 then I face the same behavior.
    I have checked "Grouping on server" option in options.
    Please Advice.
    Regards
    Asha.

    Thanks Raghavendra for reply
    How adding group will help? I have to link this command objects with view and table.Also  When I add "TOP 5000" in add command query it executes only 1 time in SQL query Profiler hower if edit that query to "TOP 5001" then it again it executes several time which is impacting the performance.
    Please advice?
    Regards
    Asha.

  • SQL Query to Calculate Total PO Amount

    Hi,
    I'm trying to create a Purchase Order view that includes Total Po Amount. Has anyone done this before and can provide me with the SQL? Or advice on how to write the query to calculate the po_line amounts for each po number?
    I've looked in the POXPOEPO.fmb form for the calculation(code) and looked at several APPS views(ie. PO_Headers_Inq_V) without any success.
    Any help would be appreciated.
    Thanks
    Tony

    Tony, I think this will help you:
    select sum(pl.unit_price * pl.quantity)
    from po_lines_all pl
    , po_headers_all ph
    where ph.segment1 = 1004257 -- po_number
    and ph.po_header_id = pl.po_header_id
    Regards,
    Ricardo Cabral

  • Sql query is taking more time

    Hi all,
    db:oracle 9i
    I am facing below query prob.
    prob is that query is taking more time 45 min than earliar (10 sec).
    please any one suggest me .....
    SQL> SELECT MAX (tdar1.ID) ID, tdar1.request_id, tdar1.lolm_transaction_id,
    2 tdar1.transaction_version
    3 FROM transaction_data_arc tdar1
    4 WHERE tdar1.transaction_name ='O96U '
    5 AND tdar1.transaction_type = 'REQUEST'
    6 AND tdar1.message_type_code ='PCN'
    7 AND NOT EXISTS (
    8 SELECT NULL
    9 FROM transaction_data_arc tdar2
    10 WHERE tdar2.request_id = tdar1.request_id
    11 AND tdar2.lolm_transaction_id != tdar1.lolm_transaction_id
    12 AND tdar2.ID > tdar1.ID)
    13 GROUP BY tdar1.request_id,
    14 tdar1.lolm_transaction_id,
    15 tdar1.transaction_version;
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=17 Card=1 Bytes=42)
    1 0 SORT (GROUP BY) (Cost=12 Card=1 Bytes=42)
    2 1 FILTER
    3 2 TABLE ACCESS (BY INDEX ROWID) OF 'TRANSACTION_DATA_ARC
    ' (Cost=1 Card=1 Bytes=42)
    4 3 INDEX (RANGE SCAN) OF 'NK_TDAR_2' (NON-UNIQUE) (Cost
    =3 Card=1)
    5 2 TABLE ACCESS (BY INDEX ROWID) OF 'TRANSACTION_DATA_ARC
    ' (Cost=5 Card=918 Bytes=20196)
    6 5 INDEX (RANGE SCAN) OF 'NK_TDAR_7' (NON-UNIQUE) (Cost
    =8 Card=4760)

    prob is that query is taking more time 45 min than earliar (10 sec).Then something must have changed (data growth/stale statistics/...?).
    You should post as much details as possible, how and what it is described in the FAQ, see:
    *3. How to improve the performance of my query? / My query is running slow*.
    When your query takes too long...
    How to post a SQL statement tuning request
    SQL and PL/SQL FAQ
    Also, given your database version, using NOT IN instead of NOT EXISTS might make a difference (but they're not the same).
    See: SQL and PL/SQL FAQ

  • Informix / SQL Query to calculate Service Level Met %

    Hi,
    We have a client running UCCX 7.0 and we are upgrading it to 8.5.
    They have a custom .net application that display different stats on IP Phone. I have converted all of them except i am having problem calculating Service Level Met %
    Existing SQL query converts boolean into Float but Informix gives error that boolean can't be converted to float or integer.
    here is part of existing query (SQl Server) to calculate service level met %
    ROUND((SUM(CAST(ssl.metServiceLevel AS FLOAT))/COUNT(CAST(ssl.metServiceLevel AS FLOAT))) * 100,2) AS serviceLevelMet
    I will greatly appreciate if anyone can help converting this query into Informix query format.
    Thank you

    Hi Sonain
    Try this, it won't display a service level until you have received at least one call on the CSQ.
    SELECT csqsum.CSQName,loggedInAgents,talkingAgents,availableAgents,workingAgents,reservedAgents,servicelevel
    FROM  RtCSQsSummary csqSum left outer join
         (SELECT csqname, ROUND(sum(100 * (MetSL)/ (case when (MetSL + NotSL  = 0) then 1 else (MetSL + NotSL) end)) ) as servicelevel
            FROM(
                SELECT
                     trim( csqname) csqname
                    ,sum( case cqd.metServiceLevel when 't' then  1 else 0 end)  MetSL
                    ,sum( case cqd.metServiceLevel when 't' then 0 else 1 end) NotSL
                FROM ContactServiceQueue csq
                    inner join contactqueuedetail cqd  on cqd.targetID = csq.recordID
                    inner join contactroutingdetail crd on crd.sessionID = cqd.sessionID
                    inner join contactcalldetail ccd on crd.sessionID = ccd.sessionID
                WHERE Date(current) - Date(crd.StartDateTime ) = 0
                GROUP BY csqname
            )z
       GROUP BY z.csqname
        )y
    ON y.CSQName = csqsum.CSQName
    Please rate helpfull posts.
    Graham

  • Need sql query to find out Joins attached with folders in Discoverer

    Hi,
    Can anyone let me know the sql query which can be used to identify the joins which are attached to the folders.
    Actually we have to identify all the joins conditions from folders those are migrated from one instance to others.
    Thanks
    abhishek

    I recommend that you implement the admin EUL supplied by oracle, you can get there a lot of repository information (metalink note: 556932.1).
    Try to use this (maybe you will need some pkg's):
    SELECT
    DECODE(KEYS.FK_MANDATORY,
    1,
    'Always exist in master folder',
    'Might not exist in master folder') "Detail Item values",
    EUL10G_US.EUL5_GET_JOIN(EXP.EXP_ID, 'N') "Join Master --> Detail",
    KEYS.KEY_DESCRIPTION JOIN_DESCRIPTION,
    KEYS.KEY_DEVELOPER_KEY JOIN_IDENTIFIER,
    KEYS.KEY_NAME JOIN_NAME,
    DECODE(SUBSTR(KEYS.KEY_NAME, 1, 19),
    'AUTO_GENERATED_NAME',
    'Yes',
    'No') "AutoGen",
    DECODE(DECODE(SUBSTR(KEYS.KEY_NAME, 1, 19),
    'AUTO_GENERATED_NAME',
    'Yes',
    'No') ,
    'Yes',
    EUL10G_US.EUL5_GET_JOIN(EXP.EXP_ID),
    KEYS.KEY_NAME) "Actual Join Name",
    KEYS.KEY_UPDATED_DATE JOIN_LAST_UPDATE,
    DECODE(KEYS.FK_ONE_TO_ONE, 1, 'One to one join', NULL) "One to One join",
    DECODE(KEYS.FK_MSTR_NO_DETAIL,
    1,
    'Outer join on detail' || CHR(10),
    NULL) "Outer Join on Detail",
    DECODE(KEYS.FK_DTL_NO_MASTER,
    1,
    'Outer join on master' || CHR(10),
    NULL) "Outer Join on Master",
    DECODE(KEYS.FK_MSTR_NO_DETAIL,
    1,
    'Outer join on detail' || CHR(10),
    NULL) || DECODE(KEYS.FK_DTL_NO_MASTER,
    1,
    'Outer join on master' || CHR(10),
    NULL) ||
    DECODE(KEYS.FK_ONE_TO_ONE, 1, 'One to one join', NULL) "Optional Join Configurations",
    OBJ.OBJ_NAME "MASTER_FOLDER",
    OBJ_DETAIL.OBJ_NAME "DETAIL_FOLDER"
    FROM EUL10G_US.EUL5_OBJS OBJ,
    EUL10G_US.EUL5_EXPRESSIONS EXP,
    EUL10G_US.EUL5_KEY_CONS KEYS,
    EUL10G_US.EUL5_OBJS OBJ_DETAIL
    WHERE ((KEYS.KEY_ID = EXP.JP_KEY_ID) AND
    (OBJ.OBJ_ID = KEYS.FK_OBJ_ID_REMOTE) AND
    (OBJ_DETAIL.OBJ_ID = keys.KEY_OBJ_ID));

  • Need sql query to find out Joins attached with folders

    Hi,
    Can anyone let me know the sql query which can be used to identify the joins which are attached to the folders.
    We dont want to see those from front end(disc admin).
    Thanks
    abhishek

    abhishek - This is the Application Express forum. I have no idea what you are asking but it may need to be directed to a different forum.
    Scott

  • Link Planning time fence with planning calendar

    Hello,
    In MD04 transaction, we can see the planning time fence lign. In my system, the planning time fence lign is calculated based on the plant calendar (SCAL transaction).
    But, we will like to calculate the planning time fence based on the planning calendar (MD26 transaction) and not on the plant calendar.
    I mean, when I close a period in the planning calendar (MD26), I want that the system establish the new planning time fence lign based on the planning calendar.
    Does anyone know if it's possible? If yes, how should I do ?
    Best regards,
    Gwen

    Hello Gwen
    The planning time fence is always calculated according to the factory calendar defined at plant level.
    If you are using a periodic lot-sizing procedure with a time fence, system may generate replenishment proposals outside the planning calendar dates, especially if you are using a goods receipt processing time. If you want to make sure that the dates will be always according to the planning calendar, you may check the following modification note:
    397870
    MOD:Procurmt propsls on non-dely date due to plng time fence
    If you want to create your own logic to calculate the time fence, you may use the BAdI MD_MRP_PARAMETERS.
    BR
    Caetano

  • SQL error msg - The DELETE statement conflicted with the SAME TABLE REFERENCE constraint

    Executed as user: ****. The DELETE statement
    conflicted with the SAME TABLE REFERENCE constraint "FK_PARENT_TASK_REF".
    The conflict occurred in database "****", table "****", column
    'PARENT_TASK_ID'. [SQLSTATE 23000] (Error 547) The statement has been
    terminated. [SQLSTATE 01000] (Error 3621). The step failed.
    Does this error msg indicate the whole script failed to execute or was it just a single step/task that failed ?
    What does error msg mean ?
    Anyway to prevent this error msg and ensure script runs successfully

    Hi mdavidh,
    This error occurs because the record  'PARENT_TASK_ID' was referenced by 'FK_PARENT_TASK_REF'.
    Please refer below codes:
    CREATE TABLE MyTable (
    ID INT, primary key(ID), -- primary key
    ID_Parent INT foreign key(ID_Parent) references MyTable(ID), -- foreign key reference the same table
    insert into MyTable(ID,ID_Parent)
    values(0,0);
    insert into MyTable(ID,ID_Parent)
    values(1,0);
    insert into MyTable(ID,ID_Parent)
    values(2,0);
    insert into MyTable(ID,ID_Parent)
    values(3,1);
    insert into MyTable(ID,ID_Parent)
    values(4,3);
    insert into MyTable(ID,ID_Parent)
    values(5,4);
    CREATE TRIGGER MyTrigger
    on MyTable
    instead of delete
    as
    set nocount on
    update MyTable set ID_Parent = null where ID_Parent in (select ID from deleted)
    delete from MyTable where ID in (select ID from deleted)
    Now we could delete records.
    delete from MyTable where ID_Parent=0
    Thanks,
    Candy Zhou

  • Sql query to calculate order completion time

    Hello,
    This is probably a textbook example, but I was wondering if someone could show me the technique to answer the following question based on the sample data:
    Show all orders from the orders table where completion time (defined as difference between time the order was completed and received). is > 5 hours
    Order_id
    Action
    Time
    1
    Received
    1/11/2014 10:12:00
    1
    Logged
    1/11/2014 10:15:00
    1
    Sent
    1/11/2014 15:15:00
    1
    Complete
    1/11/2014 16:15:00
    2
    Received
    31/10/2014 8:10
    2
    Logged
    31/10/2014 8:28
    2
    Sent
    31/10/2014 10:11
    2
    Complete
    31/10/2014 12:13
    3
    Received
    30/10/2014 13:10
    3
    Logged
    30/10/2014 15:10
    3
    Sent
    30/10/2014 16:10
    3
    Complete
    30/10/2014 17:10
    Thanks

    create table orders (order_id int, action varchar(50), [time] datetime)
    insert into orders values(1,'Received','1/11/2014 10:12'),(1,'Logged','1/11/2014 10:15'),(1,'Sent','1/11/2014 15:15'),(1,'Complete','1/11/2014 16:15'),
    (2,'Received','10/31/2014 08:10'),(2,'Logged','10/31/2014 08:28'),(2,'Sent','10/31/2014 10:11'),(2,'Complete','10/31/2014 12:13'),
    (3,'Received','10/30/2014 13:10'),(3,'Logged','10/30/2014 15:10'),(3,'Sent','10/30/2014 16:10'),(3,'Complete','10/30/2014 17:10')
    select order_id from (
    select *, datediff(hour,lag([time],1) Over(partition by order_id Order by [time]),[time]) diff
    from orders WHERE action IN ('Complete','Received')) t
    WHERE diff>=5
    drop table orders

  • Sql query taking 2 much time to execute

    hi every body
    I am trying to JOIN two tables using the following criteria
    GL_JE_LINES.GL_SL_LINK_ID = CST_AE_LINES.GL_SL_LINK_ID
    but it takes too much time .. like (1 hr r more)
    which mens that something is wrong with my logic...
    any guidance will be appreciated ....
    thnx

    Hi,
    Do you run "Gather Schema Statistics" program on regular basis?
    What is the query you are trying to run?
    Please see the following threads.
    When your query takes too long ...
    When your query takes too long ...
    Post a SQL statement tuning request - template posting
    HOW TO: Post a SQL statement tuning request - template posting
    Regards,
    Hussein

Maybe you are looking for

  • No image but screen backlight and webcam working perfect

    I own an 13' macbook pro mid 2010 and i got a problem with the display actually my Lvds connector was damaged on my logic board and got it changed but now my screen backlight and webcam only are working and i dont have any image on my display. i can

  • Cannot find my iTunes on computer at all for the past two weeks.

    I have been looking for my iTunes in my music folder and it is nowhere to be found. I have 5 ipods and have purchased many audiobooks etc...and now have no access to anything. Every time I click on the desktop icon I get this window: "The folder "iTu

  • Dreamweaver CS3 in Virtualbox on Ubuntu Intrepid

    Has anyone successfully installed and run Dreamweaver CS3 in virtualbox on Ubuntu Intrepid? Is there a definitive guide on how to do so? Any problems with network (wireless connectivity)? Any issues attaching to remote servers? Any noticeable perform

  • CS4 Colour Management question(s)

    Ok, here goes... My team of designers create adverts in InDesign that are to appear in either a newspaper OR a glossy magazine. We employ an Ad Tracking system that provides a blank InDesign template for them to work from. The Ad Tracking system know

  • Installed Windows using boot camp but lost my mac disc mid setup!

    I am on a Macbook Pro running Snow Leopard and used Boot Camp 3.0.4 to try and get Windows 7 on it. I partitioned the hard drive and successfully installed Windows 7 on my comp using my Windows 7 CD. However, being the overeager moron that I am, I di