Hi @Sarath ,
can I get the time also printed along with this. Example: 11/19/2020 7:45 AM.
have created the above code in a stored procedure and I scheduled it running for every 10 mins.
So It needs to check TargetEndTime field is null and I wanted to update this TargetEndTime only for the fields which has NULL.
For few ID the TargetEndTime may be there so those ID should not get affected.
Please refer below method:
Create a few function as below:
CREATE FUNCTION dbo.ufn_ADD_WORKING_DAYTIMES (
@DATETIME DATETIME,
@NDAYS INT
) RETURNS DATETIME
BEGIN
IF @DATETIME IS NULL
BEGIN
SET @DATETIME = GETDATE();
END
DECLARE @STARTDATE INT = 0
DECLARE @COUNT INT = 0
DECLARE @NEWDATE DATE = DATEADD(DAY, 1, @DATETIME)
WHILE @COUNT < @NDAYS
BEGIN
IF DATEPART(WEEKDAY, @NEWDATE) NOT IN (7, 1) --AND @NEWDATE NOT IN ( SELECT DT_HOLIDAY FROM TB_HOLIDAYS )
SET @COUNT += 1;
SELECT @NEWDATE = DATEADD(DAY, 1, @NEWDATE), @STARTDATE += 1;
END
RETURN DATEADD(DAY, @STARTDATE, @DATETIME);
END
GO
Call this function as below:
DROP TABLE IF EXISTS MyTable
CREATE TABLE MyTable (
ID int,
StageNumber int,
StartTime DATETIME,
TargetEndTime VARCHAR(100)
);
INSERT INTO MyTable VALUES
(101, 1, '2020-11-12 09:30:00',NULL),
(101, 2, '2020-11-13 15:23:00',NULL),
(101, 3, '2020-11-18 07:45:00','11/19/2020 07:45 PM'),
(101, 4, '2020-11-19 10:45:00',NULL);
DECLARE @StageNumber TABLE (
StageNumber int,
NumberOfDays int
);
INSERT INTO @StageNumber VALUES
(1, 2), (2, 8), (3, 5), (4, 7)
UPDATE A
SET A.TargetEndTime=FORMAT(dbo.ufn_ADD_WORKING_DAYTIMES( A.StartTime , B.NumberOfDays ),'MM/dd/yyyy hh:mm tt')
FROM MyTable A
INNER JOIN @StageNumber B
ON A.StageNumber=B.StageNumber
WHERE TargetEndTime IS NULL
SELECT * FROM MyTable
Output:
ID StageNumber StartTime TargetEndTime
101 1 2020-11-12 09:30:00.000 11/16/2020 09:30 AM
101 2 2020-11-13 15:23:00.000 11/25/2020 03:23 PM
101 3 2020-11-18 07:45:00.000 11/19/2020 07:45 PM
101 4 2020-11-19 10:45:00.000 11/30/2020 10:45 AM
3.Also for stage 9 the duration is 0.5 days so I added - (9,0.5) will this calculate 0.5 days ?
Right now both functions are not suitable for 0.5 day.
Please provide more details about this one like desired output of '2020-11-13 15:23:00.000' adding 0.5 days.
Is there any other conditions? Like 0.7 day or only 0.5 day?
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hot issues November--What can I do if my transaction log is full?
Hot issues November--How to convert Profiler trace into a SQL Server table