获得每个日期两个不同的时间3年

时间:2017-04-07 21:29:48

标签: sql-server-2008

我正在尝试创建想要数据的表 shown

有3个colume shift_date,shift#和Shift_startTime。  对于每一天,班次1和班次2,班次1班次 - 启动时间为6:30,班次2班次为16:20至2020年。

2 个答案:

答案 0 :(得分:1)

您需要的是T-SQL中的WHILE语句(https://docs.microsoft.com/en-us/sql/t-sql/language-elements/while-transact-sql)。

您可以创建一个WHILE循环,为轮班插入两行,并将变量增加一天(使用DATEADD状态)。

如果day变量高于2020年,则打破循环。

答案 1 :(得分:0)

尝试使用递归cte:

with cte1 as (
    select cast('2017-04-01' as datetime) as [Shift_Date], 
        cast(1 as smallint) as [Shift#],
        cast('2017-04-01 06:30:00.000' as datetime) as [Shift_StartTime]
    union all
    select dateadd(day, 1, [Shift_Date]), [Shift#], dateadd(day, 1, [Shift_StartTime])
    from cte1
    where dateadd(day, 1, [Shift_Date]) <= '2020-12-31'
), cte2 as (
    select cast('2017-04-01' as datetime) as [Shift_Date], 
        cast(2 as smallint) as [Shift#],
        cast('2017-04-01 16:30:00.000' as datetime) as [Shift_StartTime]
    union all
    select dateadd(day, 1, [Shift_Date]), [Shift#], dateadd(day, 1, [Shift_StartTime])
    from cte2
    where dateadd(day, 1, [Shift_Date]) <= '2020-12-31'
)
select * 
into dbo.test_shift_date_table --use you table name
from cte1
union all
select * 
from cte2
option(maxrecursion 32000)