我给两个参数begindate和enddate
示例
@begindate = '2012-01-01'
@endate = '2013-01-01'
结果为
begindate enddate
2012-01-01 00:00:00 2012-01-01 00:10:00
2012-01-01 00:10:00 2012-01-01 00:20:00
2012-01-01 00:20:00 2012-01-01 00:30:00
像这样
我写这段代码
create table Test
(
a datetime,
b datetime
)
DECLARE @BeginDate date = '2012-01-01'
DECLARE @EndDate date = '2012-12-31'
DECLARE @beginValue int = 1
DECLARE @count int = DATEDIFF ( day , '2012-01-01' , '2012-12-31' )
DECLARE @dayHours INT = 0
DECLARE @dayHoursLimit INT = 23
DECLARE @Minute INT = 0
DECLARE @MinuteLimit INT= 50
DECLARE @CountOfMinute INT =10
while @beginValue <= @count
begin
SET @BeginDate= DATEADD(DAY,1, @BeginDate);
WHILE @dayHours <= @dayHoursLimit
BEGIN
WHILE @Minute <= @MinuteLimit
BEGIN
insert into TEST
SELECT CAST(CAST(@BeginDate AS VARCHAR(10)) +' '+CAST(@dayHours AS varchar(2)) +':'+CAST (@Minute AS varchar(2)) AS datetime) as a ,
CAST(CAST(@BeginDate AS VARCHAR(10)) +' '+CAST(@dayHours AS varchar(2)) +':'+CAST (@Minute +@CountOfMinute AS varchar(2)) AS datetime) as b
0 AS B
SET @Minute = @Minute + @CountOfMinute
END
SET @Minute = 0
SET @dayHours = @dayHours +1
END
SET @dayHours = 0
SET @beginValue = @beginValue +1
END
答案 0 :(得分:0)
您希望在@BeginDate
和@EndDate
之间每隔10分钟生成一行。如果是这样,请使用递归CTE:
DECLARE @BeginDate datetime = '2012-01-01'
DECLARE @EndDate datetime = '2013-01-01'
;WITH cte AS (
SELECT @BeginDate AS BeginDate,
DATEADD(minute, 10, @BeginDate) AS EndDate
UNION ALL
SELECT DATEADD(minute, 10, BeginDate),
DATEADD(minute, 20, BeginDate)
FROM cte
WHERE BeginDate < DATEADD(minute,-10,@EndDate)
)
SELECT * FROM cte
OPTION (MAXRECURSION 0)