选择月份的第一天和当前日期之间的所有日期

时间:2012-10-11 06:59:14

标签: sql sql-server-2008

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

declare @temp table 
 (
   ddate datetime 
  ) 

我试过with cte并且我不想使用while循环,因为我想在存储过程中避免使用。

例如今天是11-oct-2012

因此临时表应该有从1-oct-201211-oct-2012

的11行

4 个答案:

答案 0 :(得分:21)

试试这个

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

答案 1 :(得分: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;

答案 2 :(得分:0)

使用current_date将每个生成的系列的天数添加到天数,系列可以从当月的第一天减去current_day到0,这样的今天02 Jun,该系列可能是(-1,0)。

答案 3 :(得分: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)