我正在尝试编写一个查询,该查询会在接下来的10年中每隔7天将一个日期插入到表中。这将使我无需手动输入这些日期。
有没有办法在每个插页上指定一个开始日期并在该日期添加7天,直到达到结束日期为止?
附件是我的查询。不知道在哪一个。任何帮助都非常感谢。
declare @startDate date
declare @endDate date
set @startDate='2015-01-03'
set @endDate='2015-01-04'
INSERT INTO TimePeriod (YearsA)
VALUES ('2015-01-03'),
('2015-01010'),
(etc.)
('2025-01-04)
答案 0 :(得分:2)
以下查询将为您提供截至2042-05-17
年的周末日期。
SELECT DISTINCT DATEADD(DAY, - DATEPART(WEEKDAY, DayNumber), CAST(DayNumber AS DATE))
FROM(
SELECT TOP (10000)
DATEADD(DAY
,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1
, CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '0101' ) DayNumber
From master..spt_values x Cross Join master..spt_values y
)x
ORDER BY DATEADD(DAY, - DATEPART(WEEKDAY, DayNumber), CAST(DayNumber AS DATE))
2015-01-03
2015-01-10
2015-01-17
2015-01-24
2015-01-31
2015-02-07
2015-02-14
2015-02-21
2015-02-28
答案 1 :(得分:1)
您可以使用递归CTE获取所有日期:
尝试;
declare @startDate date
declare @endDate date
set @startDate='2015-03-01' -- YYYY-MM-DD format
set @endDate='2015-04-01'
;with all_date as (
select @startDate Dates
union all
select DATEADD(day, 7, Dates)
from all_date
where Dates < @endDate
)
INSERT INTO TimePeriod (YearsA)
select Dates from all_date