TSQL - converting date string to datetime - sql

I have a table that has the following column (with some sample entries provided):
COLUMN NAME: pt_age_old
20 Years 8 Months 3 Weeks
1 Year 3 Months 2 Weeks
58 Years 7 Months
1 Year
7 Years 11 Months 2 Weeks
26 Years 6 Months
56 Years 6 Months
48 Years 6 Months 4 Weeks
29 Years 11 Months
4 Years 3 Months
61 Years 8 Months 4 Weeks
I have tried to cast it to datetime, of course this did not work. Same with convert.
Keep getting the following message:
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
Main 2 questions are:
Is this type of conversion even possible with this existing string format?
If so, can you steer me in the right direction so I can make this happen?
Thanks!

This could be done using custom code such as below - I've assumed the values you're using are people's ages, and you're trying to work out their date of birth given their age today.
You can see the below code in action here: http://sqlfiddle.com/#!3/c757c/2
create function dbo.AgeToDOB(#age nvarchar(32))
returns datetime
as
begin
declare #pointer int = 0
, #pointerPrev int = 1
, #y nvarchar(6)
, #m nvarchar(6)
, #w nvarchar(6)
, #d nvarchar(6)
, #result datetime = getutcdate() --set this to the date we're working to/from
--convert various ways of expressing units to a standard
set #age = REPLACE(#age,'Years','Y')
set #age = REPLACE(#age,'Year','Y')
set #age = REPLACE(#age,'Months','M')
set #age = REPLACE(#age,'Month','M')
set #age = REPLACE(#age,'Weeks','W')
set #age = REPLACE(#age,'Week','W')
set #age = REPLACE(#age,'Days','D')
set #age = REPLACE(#age,'Day','D')
set #pointer = isnull(nullif(CHARINDEX('Y',#age),0),#pointer)
set #y = case when #pointer > #pointerprev then SUBSTRING(#age,#pointerprev,#pointer - #pointerprev) else null end
set #pointerPrev = #pointer + 1
set #pointer = isnull(nullif(CHARINDEX('M',#age),0),#pointer)
set #m = case when #pointer > #pointerprev then SUBSTRING(#age,#pointerprev,#pointer - #pointerprev) else null end
set #pointerPrev = #pointer + 1
set #pointer = isnull(nullif(CHARINDEX('W',#age),0),#pointer)
set #w = case when #pointer > #pointerprev then SUBSTRING(#age,#pointerprev,#pointer - #pointerprev) else null end
set #pointerPrev = #pointer + 1
set #pointer = isnull(nullif(CHARINDEX('D',#age),0),#pointer)
set #d = case when #pointer > #pointerprev then SUBSTRING(#age,#pointerprev,#pointer - #pointerprev) else null end
set #result = dateadd(YEAR, 0 - isnull(cast(#y as int),0), #result)
set #result = dateadd(MONTH, 0 - isnull(cast(#m as int),0), #result)
set #result = dateadd(Week, 0 - isnull(cast(#w as int),0), #result)
set #result = dateadd(Day, 0 - isnull(cast(#d as int),0), #result)
return #result
end
go
select dbo.AgeToDOB( '20 Years 8 Months 3 Weeks')
NB: there's a lot of scope for optimisation here; I've left it simple above to help keep it clear what's going on.

Technically it is possible to convert the relative time label into a datetime, but you will need a reference date though (20 Years 8 Months 3 Weeks as of '2013-10-16'). The reference date is most likely today (using GETDATE() or CURRENT_TIMESTAMP), but there is a chance it is a different date. You will have to parse the label, convert it to a duration, and then apply the duration to the reference time. This will be inherently slow.
There are at least two possible ways of doing this, write a FUNCTION to parse and convert the relative time label or use a .NET extended function to do the conversion. You would need to identify all of the possible labels otherwise the conversion will fail. Keep in mind that the reference date is important since 2 months is not a constant number of days (Jan-Feb = either 58 or 59 days).
Here is a sample of what the function might look like:
-- Test data
DECLARE #test varchar(50)
, #ref_date datetime
SET #test = '20 Years 8 Months 3 Weeks'
SET #ref_date = '2013-10-16' -- or use GETDATE() / CURRENT_TIMESTAMP
-- Logic in function
DECLARE #pos int
, #ii int
, #val int
, #label varchar(50)
, #result datetime
SET #pos = 0
SET #result = #ref_date
WHILE (#pos <= LEN(#test))
BEGIN
-- Parse the value first
SET #ii = NULLIF(CHARINDEX(' ', #test, #pos), 0)
SET #label = RTRIM(LTRIM(SUBSTRING(#test, #pos, #ii - #pos)))
SET #val = CAST(#label AS int)
SET #pos = #ii + 1
-- Parse the label next
SET #ii = NULLIF(CHARINDEX(' ', #test, #pos), 0)
IF (#ii IS NULL) SET #ii = LEN(#test) + 1
SET #label = RTRIM(LTRIM(SUBSTRING(#test, #pos, #ii - #pos)))
SET #pos = #ii + 1
-- Apply the value and offset
IF (#label = 'Days') OR (#label = 'Day')
SET #result = DATEADD(dd, -#val, #result)
ELSE IF (#label = 'Weeks') OR (#label = 'Week')
SET #result = DATEADD(ww, -#val, #result)
ELSE IF (#label = 'Months') OR (#label = 'Month')
SET #result = DATEADD(mm, -#val, #result)
ELSE IF (#label = 'Years') OR (#label = 'Year')
SET #result = DATEADD(yy, -#val, #result)
END
SELECT #result
-- So if this works correctly,
-- 20 Years 8 Months 3 Weeks from 2013-10-16 == 1993-01-26

Make a function to split it up:
create function f_tst
(
#t varchar(200)
) returns date
begin
declare #a date = current_timestamp
;with split1 as
(
select 1 start, charindex(' ', #t + ' ', 4)+1 stop
where #t like '% %'
union all
select stop, charindex(' ', #t + ' ', stop + 4)+1
from split1
where charindex(' ', #t, stop) > 0
), split2 as
(
select cast(left(x.sub, charindex(' ', x.sub)) as int) number,
substring(x.sub, charindex(' ', x.sub) + 1, 1) unit
from split1
cross apply (select substring(#t, start, stop - start) sub) x
)
select #a = case unit when 'W' then dateadd(ww, -number, #a)
when 'Y' then dateadd(yy, -number, #a)
when 'M' then dateadd(mm, -number, #a)
end
from split2
return #a
end
Test function:
select dbo.f_tst(age)
from (values('20 Years 8 Months 3 Weeks'),('1 Month') ) x(age)
Result:
1993-01-27
2013-09-17

No, date time type presents actual date, like YYYY-MM-DD HH:MM, your strings are not DATE fields, they are age, to have date time you need date of birth and them somehow add this age to it

Related

SQL Server: determining the Years, Months, Weeks and Days between two dates

After reading on this topic and being advised to use DateDiff. I wrote a function that doesn't provide the answer I want. The client wants to now how long it took to complete a checklist. I have a CreationDate and CompletionDate. I need to know how many years, months, weeks and days it took. If it is 2 days then '2 days' without the years. The function deducts the number of years and then attempt to check the number of months, then the number of weeks and then the number of days. Only results are given if available. It seems DateDiff is the problem... or I am the problem not understanding DateDiff. It even returns a week for a 4 day difference in dates which doesn't make sense. It should return the number of weeks within the two dates, not caring when it starts.
This is the code
ALTER FUNCTION [dbo].[DateRangeText]
(#FromDate DATETIME, #ToDate DATETIME)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #Result AS VARCHAR(MAX);
SET #Result = '';
DECLARE #TmpS AS VARCHAR(MAX);
SET #TmpS = '';
DECLARE #Years AS INT;
SET #Years = DATEDIFF(year, #FromDate, #ToDate);
IF (#Years > 0)
BEGIN
IF (#Years = 1)
SET #TmpS = ' Year ';
ELSE
SET #TmpS = ' Years ';
SET #Result = #Result + CAST(#Years AS VARCHAR) + #TmpS;
SET #ToDate = DATEADD(YEAR, -1 * #Years, #ToDate);
END;
DECLARE #Months AS INT;
SET #Months = DATEDIFF(month, #FromDate, #ToDate);
IF (#Months > 0)
BEGIN
IF (#Months = 1)
SET #TmpS = ' Month ';
ELSE
SET #TmpS = ' Months ';
SET #Result = #Result + CAST(#Months AS VARCHAR) + #TmpS;
SET #ToDate = DATEADD(MONTH, -1 * #Months, #ToDate);
END;
DECLARE #Weeks AS INT;
SET #Weeks = DATEDIFF(week, #FromDate, #ToDate);
IF (#Weeks > 0)
BEGIN
IF (#Weeks = 1)
SET #TmpS = ' Week ';
ELSE
SET #TmpS = ' Weeks ';
SET #Result = #Result + CAST(#Weeks AS VARCHAR) + #TmpS;
SET #ToDate = DATEADD(WEEK, -1 * #Weeks, #ToDate);
END;
DECLARE #Days AS INT;
SET #Days = DATEDIFF(day, #FromDate, #ToDate);
IF (#Days > 0)
BEGIN
IF (#Days = 1)
SET #TmpS = ' Day ';
ELSE
SET #TmpS = ' Days ';
SET #Result = #Result + CAST(#Days AS VARCHAR) + #TmpS;
SET #ToDate = DATEADD(WEEK, -1 * #Days, #ToDate);
END;
IF (#Result = '')
SET #Result = 'Same day';
RETURN Rtrim(COALESCE(#Result,''));
END;
Since you are using a function, consider the following Table-Valued Function. Easy to use a stand-alone or included as a CROSS APPLY.
Performant and Accurate without having to worry about all the misc date calculations.
Example
Select * from [dbo].[tvf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())
Returns
Years Months Days Hours Minutes Seconds
26 7 5 13 47 11
The TVF if interested
CREATE FUNCTION [dbo].[tvf-Date-Elapsed] (#D1 DateTime,#D2 DateTime)
Returns Table
Return (
with cteBN(N) as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
cteRN(R) as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,#D1))From cteRN R Where DateAdd(YY,R,#D1)<=#D2),
cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D)) From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=#D2),
cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D)) From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=#D2),
cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D)) From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=#D2),
cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D)) From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=#D2),
cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D)) From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=#D2)
Select [Years] = cteYY.N
,[Months] = cteMM.N
,[Days] = cteDD.N
,[Hours] = cteHH.N
,[Minutes] = cteMI.N
,[Seconds] = cteSS.N
--,[Elapsed] = Format(cteYY.N,'0000')+':'+Format(cteMM.N,'00')+':'+Format(cteDD.N,'00')+' '+Format(cteHH.N,'00')+':'+Format(cteMI.N,'00')+':'+Format(cteSS.N,'00')
From cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[tvf-Date-Elapsed] ('1991-09-12 21:00:00.000',GetDate())
--Select * from [dbo].[tvf-Date-Elapsed] ('2017-01-01 20:30:15','2018-02-05 22:58:35')
I'll leave weeks and leap years to you to figure out unless I have time to come back to this later. However this will get you the years, months, and days you are looking for:
DECLARE #FromDate DateTime
DECLARE #ToDate DateTime
DECLARE #years INT
DECLARE #months INT
DECLARE #days INT
-- just some sample dates for testing
Set #FromDate = '01-01-2014'
Set #ToDate = GetDate()
SET #years = DATEDIFF(mm, #FromDate, #ToDate)/12
SET #months = DATEDIFF(mm, #FromDate, #ToDate)%12 - 1
SET #days = ABS(DATEDIFF(dd, DATEADD(mm,#months , DATEADD(yy, #years, #FromDate)), #ToDate))
DECLARE #YearsStr VarChar(20)
DECLARE #MonthsStr VarChar(20)
DECLARE #DaysStr VarChar(20)
SET #YearsStr = Case When #years > 0 Then Convert(varchar(10),#years) + ' Years, ' Else '' End
SET #MonthsStr = Case When #months > 0 Then Convert(varchar(10),#months) + ' Months, ' Else '' End
SET #DaysStr = Convert(varchar(10),#days) + ' Days '
SELECT #YearsStr + #MonthsStr + #DaysStr

SQL difference between dates(year,month,day)

I have a problem getting difference between two dates in years, months, days without using function, just the Select statement.
So far i have this messy code, but it doesnt work so well, as sometimes the month/day is - . tblProject.BillingDate is StartDate, tblServiceTicket.ServiceTicketDate is EndDate.
CONVERT(varchar(12),datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate)) + ' year, '
+ CONVERT(varchar(12),DATEDIFF(MM, DATEADD(YY, datediff(YEAR,tblServiceTicket.ServiceTicketDate,tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), tblProject.BillingDate)) + ' months, '
+ CONVERT(varchar(12),DATEDIFF(DD, DATEADD(MM, DATEDIFF(MM, DATEADD(YY, (datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate)), tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), DATEADD(YEAR, datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate) , tblProject.BillingDate)), tblServiceTicket.ServiceTicketDate)) + ' days '
The only way that I know to do this is semi-iteratively, like this. This version can be improved with coding around DATEDIFF, but it shows the logic needed more clearly than the DATEDIFF version.
DECLARE #dstart datetime,
#dend datetime,
#dwork datetime
DECLARE #yy int,
#mm int,
#dd int
SET #dstart = '19570125'
SET #dend = '20161214'
DECLARE #ix int
-- Get Year interval
SET #ix = 0
WHILE #ix >= 0
BEGIN
Set #ix = #ix + 1
IF Dateadd(year, #ix, #dstart) > #dend
BEGIN
SET #yy = #ix - 1
SET #ix = -1
END
END
Set #dwork = Dateadd(year, #yy, #dstart)
-- Get month interval
SET #ix = 0
WHILE #ix >= 0
BEGIN
Set #ix = #ix + 1
IF Dateadd(MONTH, #ix, #dwork) > #dend
BEGIN
SET #mm = #ix - 1
SET #ix = -1
END
END
Set #dd = DATEDIFF(day, dateadd(month, #mm, #dwork), #dend)
SELECT 'The difference is ' + Cast(#yy as varchar) + ' years, ' + Cast(#mm as varchar) + ' Months, and ' + Cast(#dd as varchar) + ' Days'
Here are some sample outputs, showing how it handles a couple of problem cases.
-- One day at new years
SET #dstart = '20161231'
SET #dend = '20170101'
-- The difference is 0 years, 0 Months, and 1 Days
-- One month to a shorter month
SET #dstart = '20160131'
SET #dend = '20170228'
-- The difference is 1 years, 1 Months, and 0 Days
-- My age
SET #dstart = '19570125'
SET #dend = '20161214'
-- The difference is 59 years, 10 Months, and 19 Days

Code error in a SQL Server While-If Loop

I know that there are other posts with code that solve my problem but I don't want to take another's code so I'm trying to do it by myself and I'm stuck with the month not increasing problem, so if anyone can help me with that mistake it will be awesome.
The problem is:
I have to populate the table Time from year 1990 to 2016 with all the months and days, I have already achieved that the code works and it populates correctly the years and the days but months increases to January (1) and then is not increasing so the table is filled with all months being January (LOL)
Here's my code:
create table Time
(
Year int,
Month int,
Day int
)
create procedure pTime
as
declare #year int, #month int, #day int;
set #year = 1990;
set #month = 12;
set #day = 10;
while(#year<=2016)
Begin
If(#day = 29)
Begin
set #month = #month + 1;
If(#month = 13)
Begin
set #month = 1;
set #day = 1;
set #year = #year + 1;
insert into Time values (#year, #month, #day);
End
End
else
Begin
If(#day = 29)
Begin
set #month = #month + 1;
set #day = 1;
insert into Time values (#year, #month, #day);
End
Else
Begin
insert into Time values (#year, #month, #day);
set #day = #day + 1;
End
End
End
Any idea where is my mistake or any suggestion?
I didn't look very closely for your mistake because SQL Server has some helpful date arithmetic functions. Here's simplified version of your stored procedure:
create procedure pTime
as
declare #theDate date = '12/10/1990', #days int = 0
while #theDate < '1/1/2016'
begin
insert into Time (Year, Month, Day) values (datepart(year, #theDate), datepart(month, #theDate), datepart(day, #theDate));
set #theDate = dateadd(day, 1, #theDate)
end
Another faster approach would be to use a tally table. Note the code below:
WITH
E(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1),
iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1))-1 FROM E a,E b,E c,E d,E e),
dates(dt) AS
(
SELECT TOP(datediff(DAY,'19900101','20160101')) DATEADD(day,N,'19900101')
FROM iTally
)
--INSERT [time] --uncomment for the insert, leave commented to see what will be inserted
SELECT YEAR(dt), MONTH(dt), DAY(dt)
FROM dates;
Why do you need If(#year = 29) condition? In your code this block never will be executed. try this:
create procedure pTime
as
declare #year int, #month int, #day int;
set #year = 1990;
set #month = 12;
set #day = 10;
while(#year<=2016)
Begin
If(#day = 29)
Begin
set #month = #month + 1;
set #day = 1;
If(#month = 13)
Begin
set #month = 1;
set #year = #year + 1;
insert into Time values (#year, #month, #day);
End
End
else
Begin
If(#day = 29)
Begin
set #month = #month + 1;
set #day = 1;
insert into Time values (#year, #month, #day);
End
Else
Begin
insert into Time values (#year, #month, #day);
set #day = #day + 1;
End
End
End
I think first assignment set #day = 1; wasn't in right place. After increasing #month value you should set also #day to 1;

Calculating due date using business hours and holidays

I need to calculate due date / end date for SLAs. As input values I have the start date and a timespan (in minutes). This calculation needs to take into account business hours, weekends, and holidays.
I've seen a lot of examples where the input is start date and end date, but have been struggling finding anything similar to the above input values.
Is there an elegant solution to this problem? Is there a way to calculate due date without using a loop? I can't think of a way to do the calculation without doing something similar to the following terrible algorithm:
Create a return variable "due date" and set it to input variable
"start date"
Create a control variable "used minutes" and set it to 0
Create a loop with the condition "used minutes" <= "input timespan"
Inside the loop, add a second to the "due date" return variable
Inside the loop, check if the second is within hours of operation
(checking business hours, weekends, and holidays). If so, increment
control variable "used minutes" by 1.
Upon exiting the loop, return variable "due date"
You need a table with valid business hours, with the weekends and holidays excluded (or marked as weekend/holiday so you can skip them.) Each row represents one day and the number of working hours for that day. Then you query the business hours table from your start date to the first (min) date where the sum(hours*60) is greater than your minutes parameter, excluding marked weekend/holiday rows. That gives you your end date.
Here's the day table:
CREATE TABLE [dbo].[tblDay](
[dt] [datetime] NOT NULL,
[dayOfWk] [int] NULL,
[dayOfWkInMo] [int] NULL,
[isWeekend] [bit] NOT NULL,
[holidayID] [int] NULL,
[workingDayCount] [int] NULL,
CONSTRAINT [PK_tblDay] PRIMARY KEY CLUSTERED
(
[dt] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
here's how I populate the table with days:
CREATE PROCEDURE [dbo].[usp_tblDay]
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#Dt datetime ,
#wkInMo int,
#firstDwOfMo int,
#holID int,
#workDayCount int,
#weekday int,
#month int,
#day int,
#isWkEnd bit
set #workDayCount = 0
SET #Dt = CONVERT( datetime, '2008-01-01' )
while #dt < '2020-01-01'
begin
delete from tblDay where dt = #dt
set #weekday = datepart( weekday, #Dt )
set #month = datepart(month,#dt)
set #day = datepart(day,#dt)
if #day = 1 -- 1st of mo
begin
set #wkInMo = 1
set #firstDwOfMo = #weekday
end
if ((#weekday = 7) or (#weekday = 1))
set #isWkEnd = 1
else
set #isWkEnd = 0
if #isWkEnd = 0 and (#month = 1 and #day = 1)
set #holID=1 -- new years on workday
else if #weekday= 6 and (#month = 12 and #day = 31)
set #holID=1 -- holiday on sat, change to fri
else if #weekday= 2 and (#month = 1 and #day = 2)
set #holID=1 -- holiday on sun, change to mon
else if #wkInMo = 3 and #weekday= 2 and #month = 1
set #holID = 2 -- mlk
else if #wkInMo = 3 and #weekday= 2 and #month = 2
set #holID = 3 -- President’s
else if #wkInMo = 4 and #weekday= 2 and #month = 5 and datepart(month,#dt+7) = 6
set #holID = 4 -- memorial on 4th mon, no 5th
else if #wkInMo = 5 and #weekday= 2 and #month = 5
set #holID = 4 -- memorial on 5th mon
else if #isWkEnd = 0 and (#month = 7 and #day = 4)
set #holID=5 -- July 4 on workday
else if #weekday= 6 and (#month = 7 and #day = 3)
set #holID=5 -- holiday on sat, change to fri
else if #weekday= 2 and (#month = 7 and #day = 5)
set #holID=5 -- holiday on sun, change to mon
else if #wkInMo = 1 and #weekday= 2 and #month = 9
set #holID = 6 -- Labor
else if #isWkEnd = 0 and (#month = 11 and #day = 11)
set #holID=7 -- Vets day on workday
else if #weekday= 6 and (#month = 11 and #day = 10)
set #holID=7 -- holiday on sat, change to fri
else if #weekday= 2 and (#month = 11 and #day = 12)
set #holID=7 -- holiday on sun, change to mon
else if #wkInMo = 4 and #weekday= 5 and #month = 11
set #holID = 8 -- thx
else if #holID = 8
set #holID = 9 -- dy after thx
else if #isWkEnd = 0 and (#month = 12 and #day = 25)
set #holID=10 -- xmas day on workday
else if #weekday= 6 and (#month = 12 and #day = 24)
set #holID=10 -- holiday on sat, change to fri
else if #weekday= 2 and (#month = 12 and #day = 26)
set #holID=10 -- holiday on sun, change to mon
else
set #holID = null
insert into tblDay select #dt,#weekday,#wkInMo,#isWkEnd,#holID,#workDayCount
if #isWkEnd=0 and #holID is null
set #workDayCount = #workDayCount + 1
set #dt = #dt + 1
if datepart( weekday, #Dt ) = #firstDwOfMo
set #wkInMo = #wkInMo + 1
end
END
I also have a holiday table, but everyone's holidays are different:
holidayID holiday rule description
1 New Year's Day Jan. 1
2 Martin Luther King Day third Mon. in Jan.
3 Presidents' Day third Mon. in Feb.
4 Memorial Day last Mon. in May
5 Independence Day 4-Jul
6 Labor Day first Mon. in Sept
7 Veterans' Day Nov. 11
8 Thanksgiving fourth Thurs. in Nov.
9 Fri after Thanksgiving Friday after Thanksgiving
10 Christmas Day Dec. 25
HTH
This is the best I could do, still uses a loop but uses date functions instead of incrementing a minutes variable. Hope you like it.
--set up our source data
declare #business_hours table
(
work_day varchar(10),
open_time varchar(8),
close_time varchar(8)
)
insert into #business_hours values ('Monday', '08:30:00', '17:00:00')
insert into #business_hours values ('Tuesday', '08:30:00', '17:00:00')
insert into #business_hours values ('Wednesday', '08:30:00', '17:00:00')
insert into #business_hours values ('Thursday', '08:30:00', '17:00:00')
insert into #business_hours values ('Friday', '08:30:00', '18:00:00')
insert into #business_hours values ('Saturday', '09:00:00', '14:00:00')
declare #holidays table
(
holiday varchar(10)
)
insert into #holidays values ('2015-01-01')
insert into #holidays values ('2015-01-02')
--Im going to assume the SLA of 2 standard business days (0900-1700) = 8*60*2 = 960
declare #start_date datetime = '2014-12-31 16:12:47'
declare #time_span int = 960-- time till due in minutes
declare #true bit = 'true'
declare #false bit = 'false'
declare #due_date datetime --our output
--other variables
declare #date_string varchar(10)
declare #today_closing datetime
declare #is_workday bit = #true
declare #is_holiday bit = #false
--Given our timespan is in minutes, lets also assume we dont care about seconds in start or due dates
set #start_date = DATEADD(ss,datepart(ss,#start_date)*-1,#start_date)
while (#time_span > 0)
begin
set #due_date = DATEADD(MINUTE,#time_span,#start_date)
set #date_string = FORMAT(DATEADD(dd, 0, DATEDIFF(dd, 0, #start_date)),'yyyy-MM-dd')
set #today_closing = (select convert(datetime,#date_string + ' ' + close_time) from #business_hours where work_day = DATENAME(weekday,#start_date))
if exists((select work_day from #business_hours where work_day = DATENAME(weekday,#start_date)))
set #is_workday = #true
else
set #is_workday = #false
if exists(select holiday from #holidays where holiday = #date_string)
set #is_holiday = #true
else
set #is_holiday = #false
if #is_workday = #true and #is_holiday = #false
begin
if #due_date > #today_closing
set #time_span = #time_span - datediff(MINUTE, #start_date, #today_closing)
else
set #time_span = #time_span - datediff(minute, #start_date, #due_date)
end
set #date_string = FORMAT(DATEADD(dd, 1, DATEDIFF(dd, 0, #start_date)),'yyyy-MM-dd')
set #start_date = CONVERT(datetime, #date_string + ' ' + isnull((select open_time from #business_hours where work_day = DATENAME(weekday,convert(datetime,#date_string))),''))
end
select #due_date
Sql to Calculate due date excluding holidays and considering business hour as below :- < note : - It's working correctly Business hour (8-5) Maintain holiday table
CREATE TABLE [dbo].[holiday](
[id] [int] IDENTITY(1,1) NOT NULL,
[region] [nvarchar](10) NULL,
[Hdate] [date] NULL,
)
>
declare #start datetime= getdate()
declare #slamins int =960 --- SLA time in mins
declare #Country varchar(2)='NA'
declare #start_hour int = 8 -- business start hour
declare #end_hour int = 17 -- business end hour
declare #true bit = 'true'
declare #false bit = 'false'
declare #is_workday bit = #true
declare #is_holiday bit = #false
declare #due_date datetime
declare #today_closing datetime
declare #temp int = 0
declare #holidays table (HDate DateTime) -- Table variable to hold holidayes
---- Get country holidays from table based on the country code (Feel free to remove this or modify as per your DB schema)
Insert Into #Holidays (HDate) Select date from HOLIDAY Where region=#Country and Hdate>=DateAdd(dd, DateDiff(dd,0,#start), 0)
--check for weekends
set #start = case(datepart(dw,#start)+##datefirst-1)%7
when 0 then Convert(dateTime,CONVERT(varchar,#start+1,101)+' 08:00:00')
when 6 then Convert(dateTime,CONVERT(varchar,#start+2,101)+' 08:00:00')
else #start end
-- check if start time is before business hour
if datepart(hh, #start) < #start_hour set #start = Convert(dateTime,CONVERT(varchar,#start,101)+' 08:00:00')
-- check if start time is after business hour
if datepart(hh, #start) >= #end_hour set #start = Convert(dateTime,CONVERT(varchar,#start+1,101)+' 08:00:00')
-- loop start
while (#slamins > 0)
begin
-- prepared closing date time based on start date
set #today_closing = Convert(dateTime,CONVERT(varchar,#start,101)+' 17:00:00')
set #due_date = #start
-- calculate number of Minute between start date and closing date
set #temp = DATEDIFF(N, #start , #today_closing);
--check for weekends
if (DATEPART(dw, #start)!=1 AND DATEPART(dw, #start)!=7)
set #is_workday = #true
else
set #is_workday = #false
--check for holidays
if (Select Count(*) From #Holidays Where HDATE=DateAdd(dd, DateDiff(dd,0,#start), 0)) = 0
set #is_holiday =#false
else
set #is_holiday = #true
if #is_workday = #true and #is_holiday = #false
begin
if(#temp < #slamins)
begin
set #slamins = #slamins - #temp
end
else
begin
set #due_date = DATEADD(MINUTE,#slamins,#start)
set #slamins = 0
print #due_date
end
end
set #start = Convert(dateTime,CONVERT(varchar,#start+1,101)+' 08:00:00')
end
select #due_date
Here is an option using a WorkSchedule table, which will contain the business hours that are available to count towards the SLA. To account for weekends and holidays, just do not insert records for these days into the WorkSchedule table.
This solution also uses a "Tally" table aka numbers table in the due date calc. I also included debug output to help you see what is going on, so just comment out or uncomment any debug sections to see less/more info.
I used SQL temp tables in this example so that you can run it without messing up your current database schema, but you should replace with physical tables if you use this solution.
Test Data setups:
CREATE TABLE #WorkSchedule(WorkStart datetime not null primary key, WorkEnd datetime not null);
GO
CREATE TABLE #Tally (N int not null primary key);
GO
--POPULATE TEST DATA
--populate Tally table
insert into #Tally (N)
select top 10000 N = row_number() over(order by o.object_id)
from sys.objects o cross apply sys.objects o2
;
go
--POPULATE WITH DUMMY TEST DATA
INSERT INTO #WorkSchedule(WorkStart, WorkEnd)
SELECT
workStart = dateadd(hour, 8, t.workDate)
, workEnd = dateadd(hour, 17, t.workDate)
FROM (
SELECT top 10000 workDate = dateadd(day, row_number() over(order by o.object_id), '2000-01-01')
FROM sys.objects o cross apply sys.objects o2
) t
--Exclude weekends from work schedule
WHERE datename(weekday, t.workDate) not in ('Saturday','Sunday')
;
GO
Code to calculate Due Date:
SET NOCOUNT ON;
DECLARE #startDate datetime;
DECLARE #SLA_timespan_mins int;
DECLARE #workStartDayOne datetime;
DECLARE #SLA_Adjusted int;
DECLARE #dueDate datetime;
--SET PARAM VALUES HERE FOR TESTING TO ANY DATE/SLA TIMESPAN YOU WANT:
SET #startDate = '2014-01-04 05:00'; --Saturday
SET #SLA_timespan_mins = 10 * 60 ; --10 hrs.
--get the info day 1, since your start date might be after the work start time.
select top 1 #workStartDayOne = s.WorkStart
--increase the SLA timespan mins to account for difference between work start and start time
, #SLA_Adjusted = case when #startDate > s.WorkStart then datediff(minute, s.WorkStart, #startDate) else 0 end + #SLA_timespan_mins
from #WorkSchedule s
where s.WorkEnd > #startDate
and s.WorkStart <> s.WorkEnd
order by s.WorkStart asc
;
--DEBUG info:
select 'Debug Info' as DebugInfo, #startDate AS StartDate, #workStartDayOne as workStartDayOne, #SLA_timespan_mins as SLA_timespan_mins, #SLA_Adjusted as SLA_Adjusted;
--now sum all the non work hours during that period and determine the additional mins that need added.
;with cteWorkMins as
(
SELECT TOP (#SLA_Adjusted)
s.WorkStart, s.WorkEnd
, WorkMinute = dateadd(minute, t.N, cast(s.WorkStart as datetime))
, t.N as MinuteOfWorkDay
, RowNum = row_number() over(order by s.WorkStart, t.N)
FROM #WorkSchedule s
INNER JOIN #Tally t
ON t.N between 1 and datediff(minute, s.WorkStart, s.WorkEnd)
WHERE s.WorkStart >= #workStartDayOne
ORDER BY s.WorkStart, t.N
)
/**/
SELECT #dueDate = m.WorkMinute
FROM cteWorkMins m
WHERE m.RowNum = #SLA_Adjusted
--*/
/**
--DEBUG: this query will show every minute that is accounted for during the Due Date calculation.
SELECT m.*
FROM cteWorkMins m
--WHERE m.RowNum = #SLA_Adjusted
ORDER BY m.WorkMinute
--*/
;
select #dueDate as DueDate;
GO
Test Cleanup:
IF object_id('TEMPDB..#WorkSchedule') IS NOT NULL
DROP TABLE #WorkSchedule;
GO
IF object_id('TEMPDB..#Tally') IS NOT NULL
DROP TABLE #Tally;
GO
as I understood from your question, what you need is as follow
You have given start date and number of minutes added to it, then you need to get the due date
To get the due date, you need to exclude the holidays and the due date should be during business day
here is what you can do
declare #start datetime,
#min int,
#days int
set #start= '28 Dec 2014'
set #min = 2200
-- get the number of days
set #days=datediff(day,#start,dateadd(minute,#min,#start))
-- get the due date
select max(Date)
from
(select row_number() over( order by t.Id)-1 as Id,t.Date
from DateMetadata t
inner join BusinessDays b on Day(t.Date) = b.Day
where t.Date > = #start and not exists(select 1 from Holidays h
where h.Day=Day(t.Date)
and h.Month=Month(t.Date))) as p
where p.Id < #days
Note :that DateMetadata table you will setup it in your database once
the setup for the above code :
create table Holidays(Id int identity(1,1),
Name nvarchar(50),
Day int,
Month int)
create table BusinessDays(Id int identity(1,1),
Name nvarchar(20),
Day int)
-- i am putting some days that are known,
-- it depends on you to define which holidays you want
insert into Holidays (Name,Day,Month) values('Christmas',25,12)
insert into Holidays(Name,Day,Month) values('New Year',31,12)
insert into Holidays(Name,Day,Month) values('Valentine',14,2)
insert into Holidays(Name,Day,Month) values('Mothers day',21,3)
insert into Holidays(Name,Day,Month) values('April fools day',1,4)
-- i am assuming that the business days are from monday till friday and
-- saturday and sunday are off days
insert into BusinessDays(Name,Day) values ('Monday',1)
insert into BusinessDays(Name,Day) values('Tuesday',2)
insert into BusinessDays(Name,Day) values('Wednesday',3)
insert into BusinessDays(Name,Day) values('Thursday',4)
insert into BusinessDays(Name,Day) values('Friday',5)
this table is needed and you will setup it once
-- set up a table that contains all dates from now till 2050 for example
-- and you can change the value of 2050 depending on your needs
-- this table you will setup it once
create table DateMetadata(Id int identity(1,1),
Date datetime)
declare #date datetime
set #date='01 Jan 2014'
while #date < '31 Dec 2050'
begin
insert into DateMetadata(Date) values(#date)
set #date = #date + 1
end
here a working DEMO
if you need any explanation, i am ready
hope it will help you
I created a function to calculate due date from the table, once it's populated as per Beth's and others' approaches (various similar methods for doing this, as you can see -- it only took me about an hour to think about all the UK holidays and populate the table including Easter dates up to 2029 without using these exact guides).
Note that my table contains SLA in business hours (8 hours in a normal day, 5 days in a normal week), your business hours may vary but you can amend this easily, just make sure your business hours are set the same for both the SLA table and the function below.
Code below is T-SQL (written in SSMS v17.8.1)
CREATE FUNCTION [JIRA].[Fn_JIRA_Due_Date] (
#CreatedDate DATETIME, #SLA_Business_Hours INTEGER
) RETURNS DATETIME
AS
-- SELECT [JIRA].[Fn_JIRA_Due_Date]('2019-12-28 08:00:00', 24)
/*
baldmosherâ„¢
2019-03-25
* Function returns the DueDate for a JIRA ticket, based on the CreatedDate and the SLA (based on the Issue Type, or the Epic for Tasks) and business hours per date (set in [JIRA].[Ref_JIRA_Business_Hours])
* Called by IUP to store this at the time the ticket is loaded
* Can only consider SLA in Business Hours:
* <24hrs calendar = <8hrs business
* =24hrs calendar = 8hrs business
* >24hrs calendar = 8hrs business * business days
*/
BEGIN
IF #CreatedDate IS NULL OR #SLA_Business_Hours IS NULL RETURN NULL;
DECLARE #SLA_Hours_Remaining SMALLINT = #SLA_Business_Hours;
--SET DATEFIRST 1;
DECLARE #DueDate DATETIME;
DECLARE #BusHrsStart DECIMAL(18,10) = 8 ; -- start of Business Hours (8am)
DECLARE #BusHrsClose DECIMAL(18,10) = 16 ; -- close of Business Hours (4pm)
--DECLARE #WkndStart DECIMAL(18,10) = 6 ; -- start of weekend (Sat)
DECLARE #Hours_Today SMALLINT ; -- # hours left in day to process ticket
-- PRINT 'Created ' + CAST(CAST(#CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(#CreatedDate AS TIME) AS VARCHAR(8))
--!!!! extend to the next whole hour just to simplify reporting -- need to work on fixing this eventually
SET #CreatedDate = DATEADD(MINUTE,60-DATEPART(MINUTE,#CreatedDate),#CreatedDate)
-- PRINT 'Rounded ' + CAST(CAST(#CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(#CreatedDate AS TIME) AS VARCHAR(8))
--check if created outside business hours and adjust CreatedDate to start the clock first thing at the next business hours start of day (days are checked next)
IF DATEPART(HOUR,#CreatedDate) < #BusHrsStart
--created before normal hours, adjust #CreatedDate later to #BusHrsStart same day
BEGIN
SET #CreatedDate = DATEADD(HOUR,#BusHrsStart,CAST(CAST(#CreatedDate AS DATE) AS DATETIME))
END
IF DATEPART(HOUR,#CreatedDate) >= #BusHrsClose
--created after normal hours, adjust #CreatedDate to #BusHrsStart next day
BEGIN
SET #CreatedDate = DATEADD(HOUR,#BusHrsStart,CAST(CAST(#CreatedDate+1 AS DATE) AS DATETIME))
--adjust CreatedDate to start the clock the next day with >0 business hours (i.e. extend if it falls on a weekend or holiday)
SET #CreatedDate = CAST(#CreatedDate AS DATE)
StartNextWorkingDay:
IF (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = #CreatedDate ORDER BY [Date]) = 0
BEGIN
SET #CreatedDate = DATEADD(DAY,1,#CreatedDate)
GOTO StartNextWorkingDay
END
--DATEADD(DAY, DATEDIFF(DAY,0,#CreatedDate+7)/7*7,0); -- midnight, Monday next week
SET #CreatedDate = DATEADD(HOUR,#BusHrsStart,#CreatedDate); -- BusHrsStart
END
-- PRINT 'Started ' + CAST(CAST(#CreatedDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(#CreatedDate AS TIME) AS VARCHAR(8))
--third, check the business hours for each date from CreatedDate onwards to determine the relevant DueDate
SET #DueDate = #CreatedDate
-- PRINT 'SLA Hrs ' + CAST(#SLA_Hours_Remaining AS VARCHAR(2))
SET #Hours_Today = #BusHrsStart + (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = CAST(#DueDate AS DATE) ORDER BY [Date]) - DATEPART(HOUR, #CreatedDate)
-- PRINT 'Hrs Today ' + CAST(#Hours_Today AS VARCHAR(2))
DueNextWorkingDay:
IF #SLA_Hours_Remaining > #Hours_Today
BEGIN
-- PRINT 'Due another day'
SET #SLA_Hours_Remaining = #SLA_Hours_Remaining - #Hours_Today --adjust remaining time after today's hours
SET #Hours_Today = (SELECT TOP(1) [Business_Hours] FROM [JIRA].[Ref_JIRA_Business_Hours] b WHERE b.[Date] = CAST(#DueDate AS DATE) ORDER BY [Date])
-- PRINT 'SLA Hrs ' + CAST(#SLA_Hours_Remaining AS VARCHAR(2))
-- PRINT 'Hrs Today ' + CAST(#Hours_Today AS VARCHAR(2))
SET #DueDate = DATEADD(DAY,1,DATEADD(HOUR,#BusHrsStart,CAST(CAST(#DueDate AS DATE) AS DATETIME))) --adjust DueDate to first thing next day
END
IF #SLA_Hours_Remaining <= #Hours_Today
BEGIN
-- PRINT 'Due today'
SET #DueDate = DATEADD(HOUR,#SLA_Hours_Remaining,#DueDate)
END
ELSE
BEGIN
GOTO DueNextWorkingDay
END
-- PRINT 'DueDate ' + CAST(CAST(#DueDate AS DATE) AS VARCHAR(10)) + ' ' + CAST(CAST(#DueDate AS TIME) AS VARCHAR(8))
RETURN #DueDate
END
GO
Table for SLAs:
CREATE TABLE [JIRA].[Ref_JIRA_SLAs](
[SLA_SK] [SMALLINT] IDENTITY(1,1) NOT NULL,
[Project] [VARCHAR](20) NULL,
[Issue_Type] [VARCHAR](50) NULL,
[Epic_Name] [VARCHAR](50) NULL,
[SLA_Business_Hours] [SMALLINT] NULL,
[Comments] [VARCHAR](8000) NULL
) ON [PRIMARY] WITH (DATA_COMPRESSION = PAGE)
GO

Display Employee Name, Dept Name, Salary, Grade, Experience (EX: XX Years YY Months ZZ Days) for all the employees in SQL

please help in the following query
Display Employee Name, Dept Name, Salary, Grade, Experience (EX: XX Years YY Months ZZ Days) for all the employees
ENAME DNAME SAL GRADE EXPERIENCE
SCOTT RESEARCH 3000 4 12 Years 3 months 15 days
like this i need to get the output.
i have tried to write upto years but months,days i am not able to get.
select distinct ename,dname,sal,grade,
(round((months_between(sysdate,hiredate)/12))||' years' EXP
from emp,salgrade,dept
where dept.deptno=emp.deptno and sal between losal and highsal;
You have got the years.
Use MONTHS_BETWEEN(date1, date2) to get months. Then subtract (year * 12).
Use DAYS_BETWEEN(date1, date2) to get number of days.
See this for more details
Here's a T-SQL (SQL Server) solution which I've got working (based on tests so far). Sadly I don't have an oracle instance to play on, but hopefully this shouldn't be too hard to convert:
declare #fromDate date = '2010-11-21'
, #toDate date = getutcdate()
--from date must be before to date
declare #tempDate date
if #toDate < #fromDate
begin
set #tempDate = #toDate
set #toDate = #fromDate
set #fromDate = #tempDate
end
declare #fDD int = datepart(dd,#fromdate)
, #tDD int = datepart(dd,#todate)
, #fMM int = datepart(mm,#fromdate)
, #tMM int = datepart(mm,#todate)
, #fYYYY int = datepart(yyyy,#fromdate)
, #tYYYY int = datepart(yyyy,#todate)
, #y int, #m int, #d int
--calc difference in years
set #y = #tYYYY-#fyyyy
if #fMM > #tMM or (#fMM=#tMM and #fDD > #tDD)
begin
set #y = #y - 1
set #fYYYY = #fYYYY + #y
set #tempDate = DATEADD(year,#y,#fromDate)
end
--calc remaining difference in months
set #m = DATEDIFF(month,#tempDate,#toDate)
if #tDD < #fDD
begin
set #m = #m-1
set #tempDate = DATEADD(month,#m,#tempDate)
end
--calc remaining difference in days
set #d = DATEDIFF(day,#tempDate,#toDate)
--display results in user friendly and grammatically correct way
select cast(#y as nvarchar(3)) + N' year' + case when #y = 1 then N'' else N's' end + N' '
+ cast(#m as nvarchar(2)) + N' month' + case when #m = 1 then N'' else N's' end + N' '
+ cast(#d as nvarchar(3)) + N' day' + case when #d = 1 then N'' else N's' end + N' '
Here is your required answer in ORACLE SQL
select (floor(months_between(sysdate,hiredate)/12)) YEARS,
round(((months_between(sysdate,hiredate)/12)-(round(months_between(sysdate,hiredate)/12)))*12) months
from abc;