Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all dates between first day of month and current date

Just want to select all dates between cureent date and first day of month . I want to use fill all dates in a temp table

declare @temp table 
 (
   ddate datetime 
  ) 

I have tried with with cte and i don't want to use while loop becuase i want to avoid while in stored procedure .

For example as today is 11-oct-2012

so temp table should have 11 rows starting from 1-oct-2012 to 11-oct-2012

like image 894
rahularyansharma Avatar asked Nov 29 '22 02:11

rahularyansharma


2 Answers

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

like image 122
Niladri Biswas Avatar answered Dec 21 '22 08:12

Niladri Biswas


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;
like image 35
RichardTheKiwi Avatar answered Dec 21 '22 08:12

RichardTheKiwi