Replace in Date inside a FOR

Asked

Viewed 46 times

2

I want to return the last 12 months, the day should come as 01 and need month and year. ex:

2014-12-01
2014-11-01

NOTE: I put yyyy-mm-dd only by a pattern of mine.

I’m doing like this:

DECLARE @count INT
DECLARE @Data_Atual DATE
SET @count = 0
WHILE (@count < 12)
BEGIN
   SET @count = (@count + 1)    -- count++

   SET @Data_Atual = DATEADD(month, -@count, GETDATE()) --as 12 datas


   print @Data_Atual

END

The problem that today 08 is returning:

2014-12-08
2014-11-08
2014-10-08
2014-09-08
2014-08-08
2014-07-08
2014-06-08
2014-05-08
2014-04-08
2014-03-08
2014-02-08
2014-01-08

and I want to do a replace on the day for 01, whatever the shape. but I need it to remain a DATE type because I will use it in a select ...

1 answer

3


Keeping your algorithm, add this line that will set in @Data_Atual the first day of the month itself @Data_Atual:

SET @Data_Atual = DATEADD(month, DATEDIFF(month, 0, @Data_Atual), 0)
  • 3

    Great coffee, congratulations, it worked, after this I’ll even drink a coffee..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.