如果我有一个带有StartDate列和EndDate列的表,我可以生成一个返回包含该范围内每一天的集合的查询。我可以使用表变量并执行一些过程代码,但我想知道是否有办法在查询中执行此操作。
E.g。 StartDate = 1/1/2010,EndDate = 1/5/2010,结果为:
...表格中包含StartDate和EndDate列的每一行。
*我正在使用SQL 2005
答案 0 :(得分:2)
SQL Server 2005 +:
WITH dates AS (
SELECT t.startdate 'date'
FROM TABLE t
WHERE t.startdate = '1/1/2010'
UNION ALL
SELECT DATEADD(dd, 1, t.date)
FROM dates t
WHERE DATEADD(dd, 1, t.date) <= (SELECT t.enddate FROM TABLE t WHERE t.enddate = '1/5/2010'))
SELECT ...
FROM TABLE t
JOIN dates d ON d.date = t.date
如果您的日期不超过2047天:
SELECT DATEADD(day,
n.number,
(SELECT t.startdate FROM TABLE t WHERE t.startdate = '1/1/2010')
)
FROM (SELECT DISTINCT number
FROM MASTER.dbo.SPT_VALUES
WHERE name IS NULL) n
WHERE DATEADD(day, n.number, (SELECT t.startdate FROM TABLE t WHERE t.startdate = '1/1/2010')) <= (SELECT t.endate FROM TABLE t WHERE t.endate = '1/5/2010')
答案 1 :(得分:0)
with DateList as
(
select cast('1/1/2010' as datetime) DateValue
union all
select DateValue + 1
from DateList
where DateValue + 1 >= '1/1/2010' AND DateValue +1 <= '1/5/2010'
)
select CONVERT(varchar, DateValue, 101)
from DateList
OPTION (MAXRECURSION 0)