SQL to find time elapsed from multiple overlapping intervals

后端 未结 3 1905
-上瘾入骨i
-上瘾入骨i 2020-12-05 20:50

Not using MSSQL or DB2 or Oracle. No CTE. No OVERLAP predicate. No INTERVAL data type. The situation: on a vehicle to be repaired work can not start until all parts orde

3条回答
  •  心在旅途
    2020-12-05 21:44

    USE [DnnMasterShoraSystem]
    GO
    /****** Object:  StoredProcedure [dbo].[CalculateHoldTimes]    Script Date: 12/8/2014 1:36:12 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    ALTER PROCEDURE [dbo].[CalculateHoldTimes]
        @PID int    
    AS
    BEGIN      
    CREATE TABLE #tblTemp(
        [ID] [int] NOT NULL,
        [PID] [int] NOT NULL,
        [BID] [int] NOT NULL,
        [Active] [bit] NULL,
        [WorkStartDate] [nvarchar](10) NULL,
        [WorkEndDate] [nvarchar](10) NULL,
        [jobStateID] [int] NULL,
        [RegisterType] [int] NULL,
        [RegisterState] [int] NULL,
        [En_time] [datetime] NULL,
        [Fa_time] [nvarchar](40) NULL,
        [Status] [nvarchar](100) NULL,
        [PortalId] [int] NULL,
        [ModuleId] [int] NULL,
        [UserId] [int] NULL,
        [BrName] [nvarchar](150) NULL,
        [BrCode] [nvarchar](20) NULL,
        [WorkEndDate_New] [nvarchar](10) NULL
    ) ON [PRIMARY]
    
    insert into #tblTemp
    select * from [dbo].[Shora.Personel_Branch_Copy] 
            where WorkStartDate is not null 
            --and [dbo].[ShamsiToMiladi](WorkStartDate) @Period_End
            begin
                set @Period_Start=@SDate            
    
                if @Period_End>=@Period_Start
                set @Total+=DATEDIFF(DAY,@Period_Start,@Period_End)
            end
        else if @SDate<@Period_End
            begin       
            set @Period_Start=@Period_Start     
                set @Total=DATEDIFF(DAY,@Period_Start,@Period_End)
            end
    
            set @OldSDate=@SDate 
            set @OldEDate=@EDate
    
            FETCH NEXT FROM Events
            INTO @SDate, @EDate;
    
            if  @Period_End<@EDate
            set @Period_End=@EDate
    
        END;
    
    INSERT INTO [dbo].[PersonelDays]
               (PID
               ,[Total_Start]
               ,[Total_End]
               ,[Total_count])
         VALUES
               (@PID,           
                @Period_Start,
                @Period_End,
                @Total
               )
    
    drop table #tblTemp
    CLOSE Events
    DEALLOCATE Events
    END;
    

提交回复
热议问题