4

只想选择当前日期和月份第一天之间的所有日期。我想使用填充临时表中的所有日期

declare @temp table 
 (
   ddate datetime 
  ) 

我已经尝试过 with cte ,但我不想使用 while 循环,因为我想避免 while 在存储过程中。

例如今天是11-oct-2012

所以临时表应该有 11 行从1-oct-2012to11-oct-2012

4

4 回答 4

22

Try this

DECLARE @startDate DATE=CAST(MONTH(GETDATE()) AS VARCHAR) + '/' + '01/' +  + CAST(YEAR(GETDATE()) AS VARCHAR)  -- mm/dd/yyyy
DECLARE @endDate DATE=GETDATE() -- mm/dd/yyyy

SELECT [Date] = DATEADD(Day,Number,@startDate) 
FROM  master..spt_values 
WHERE Type='P'
AND DATEADD(day,Number,@startDate) <= @endDate

OR

DECLARE @startDate DATETIME=CAST(MONTH(GETDATE()) AS VARCHAR) + '/' + '01/' +  + CAST(YEAR(GETDATE()) AS VARCHAR) -- mm/dd/yyyy
DECLARE @endDate DATETIME= GETDATE() -- mm/dd/yyyy

;WITH Calender AS 
(
    SELECT @startDate AS CalanderDate
    UNION ALL
    SELECT CalanderDate + 1 FROM Calender
    WHERE CalanderDate + 1 <= @endDate
)
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25) 
FROM Calender
OPTION (MAXRECURSION 0)

enter image description here

于 2012-10-11T07:08:56.183 回答
3
declare @temp table (ddate datetime);

insert @temp
select DATEDIFF(d,0,GetDate()-Number)
from master..spt_values
where type='p' and number < DatePart(d,Getdate())
order by 1;
于 2012-10-11T07:56:45.143 回答
0

使用 current_date 将每个生成的系列的天数添加到天数中,该系列可以从该月的第一天减去 current_day 到 0,例如今天 6 月 2 日,该系列可以是 (-1, 0)。

于 2018-06-02T03:15:31.670 回答
0

试试下面的代码:

DECLARE @startDate DATETIME=CAST(MONTH(GETDATE()) AS VARCHAR) + '/' + '01/' +  + CAST(YEAR(GETDATE()) AS VARCHAR) -- mm/dd/yyyy
DECLARE @endDate DATETIME= CAST(MONTH(GETDATE()) AS VARCHAR) + '/' + '31/' +  + CAST(YEAR(GETDATE()) AS VARCHAR) -- mm/dd/yyyy

;WITH Calender AS 
(
    SELECT @startDate AS CalanderDate
    UNION ALL
    SELECT CalanderDate + 1 FROM Calender
    WHERE CalanderDate + 1 <= @endDate
)
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25) 
FROM Calender
OPTION (MAXRECURSION 0)
于 2019-10-01T14:57:42.680 回答