SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Shift Date
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

samir.first
Starting Member

Egypt
28 Posts

Posted - 12/09/2013 :  07:41:01  Show Profile  Reply with Quote
DECLARE @startDate DATETIME = '2013-12-09 08:00:00' , @EndDate DATETIME = '2013-12-11 20:00:00'

ShiftOn = 8
ShiftTow = 4
ShiftThree = 12
I need Table Contain
DateTimeFrom DateTimeTO Shift
2013-12-09 08:00 2013-12-09 12:00 ShiftOne
2013-12-09 12:00 2013-12-09 16:00 ShiftTow
2013-12-09 16:00 2013-12-09 24:00 ShiftThree
2013-12-10 08:00 2013-12-10 12:00 ShiftOne
2013-12-10 12:00 2013-12-10 16:00 ShiftTow
2013-12-10 16:00 2013-12-10 24:00 ShiftThree
... etc

webfred
Flowing Fount of Yak Knowledge

Germany
8760 Posts

Posted - 12/09/2013 :  07:46:06  Show Profile  Visit webfred's Homepage  Reply with Quote
maybe you mean 4,4,8 and not 8,4,12?


Too old to Rock'n'Roll too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52309 Posts

Posted - 12/09/2013 :  09:06:48  Show Profile  Reply with Quote

DECLARE @startDate DATETIME = '2013-12-09 08:00:00' , @EndDate DATETIME = '2013-12-11 20:00:00'

DECLARE @ShiftOn int= 8
DECLARE @ShiftTow int = 4 
DECLARE @ShiftThree int = 12



;With CTE
AS
(
SELECT DATEADD(hh,@ShiftOn,DATEADD(dd,DATEDIFF(dd,0,@startDate),0)) AS DateVal,1 AS Cnt
UNION ALL
SELECT DATEADD(hh,CASE WHEN Cnt % 3 = 0  THEN @ShiftOn WHEN Cnt % 3 = 1  THEN @ShiftTow WHEN Cnt % 3 = 2  THEN  @ShiftThree ELSE 0 END,DateVal),Cnt + 1
FROM CTE
WHERE DATEADD(hh,CASE WHEN Cnt % 3 = 0  THEN @ShiftOn WHEN Cnt % 3 = 1  THEN @ShiftTow WHEN Cnt % 3 = 2  THEN  @ShiftThree ELSE 0 END,DateVal) <= @EndDate
)
SELECT c1.DateVal,c2.DateVal
FROM CTE c1
JOIN CTE c2
ON c2.Cnt = c1.Cnt + 1
AND DATEPART(hh,c1.DateVal ) >= @ShiftOn

output
-------------------------------------------------
DateVal	                DateVal
-------------------------------------------------
2013-12-09 08:00:00.000	2013-12-09 12:00:00.000
2013-12-09 12:00:00.000	2013-12-10 00:00:00.000
2013-12-10 08:00:00.000	2013-12-10 12:00:00.000
2013-12-10 12:00:00.000	2013-12-11 00:00:00.000
2013-12-11 08:00:00.000	2013-12-11 12:00:00.000



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000