在SQL Server中,我希望从日期到日期获得好几天。示例:从2015/12/28
到2016/01/02
,结果为
2015/12/28
2015/12/29
2015/12/30
2015/12/31
2016/01/01
2016/01/02
DECLARE @STARTDATE DATETIME = '2015-12-28'
DECLARE @ENDDATE DATETIME = '2016-01-02'
SELECT BETWEEN @STARTDATE AND @ENDDATE AS DAYS
答案 0 :(得分:4)
使用 CTE
DECLARE @STARTDATE DATE = '2015-12-28'
DECLARE @ENDDATE DATE = '2016-01-02'
;WITH CTE AS
(
SELECT @STARTDATE As dt
UNION ALL
SELECT DATEADD(D,1,dt) AS dt
FROM CTE
WHERE dt < @ENDDATE
)
SELECT * FROM CTE
答案 1 :(得分:3)
You could build a calendar table,这可能会派上用场。或者你可以使用循环。
DECLARE @ENDDATE DATETIME = '2016-01-02'
DECLARE @DAY DATETIME = '2015-12-28'
WHILE @Day <= @ENDDATE
BEGIN
SELECT @DAY
SET @DAY = DATEADD(DD,1,@DAY)
END
或者在一个结果集中的所有日子:
DECLARE @ENDDATE DATETIME = '2016-01-02'
DECLARE @DAY DATETIME = '2015-12-28'
DECLARE @TABLE TABLE (DATE DATETIME)
WHILE @Day <= @ENDDATE
BEGIN
INSERT @TABLE
VALUES (@DAY)
SET @DAY = DATEADD(DD,1,@DAY)
END
SELECT *
FROM @TABLE
答案 2 :(得分:0)
您可以在WHERE子句中指定日期。例如,WHERE日期&gt; = @ STARTDATE和日期&lt; = @ ENDDATE。这应该返回结果中的完整日期。
答案 3 :(得分:0)
使用Numbers表
dict.__len__