PhoenixUNI
PhoenixUNI

Reputation: 67

Get Start of Year based on Last Month

I run a stored procedure on the 1st of the month that takes all data from the previous month and puts it into another table. I do it as follows:

DECLARE @startOfCurrentMonth DATETIME
SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)

insert into ThisTable
select Things
from AnotherTable
where AppsEntryDate >= DATEADD(month, -1, @startOfCurrentMonth)
and AppsEntryDate < @startOfCurrentMonth

I now need to build another query that does this on a yearly basis. So, right now it's March. I need to enter all the data from Jan 1 2015 through Feb 28 2015 using this same structure. The trick is, on Jan 1 2016, I need it to capture all data from 2015. How would I code this?

Upvotes: 0

Views: 110

Answers (1)

PhoenixUNI
PhoenixUNI

Reputation: 67

Figured out what I needed to do.

DECLARE @startOfCurrentMonth DATETIME
DECLARE @endOfLastMonth DATETIME
DECLARE @startOfYear DATETIME

SET @startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
SET @endOfLastMonth = DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0))
SET @startOfYear = DATEADD(yy, DATEDIFF(yy, 0, @endOfLastMonth), 0)

Upvotes: 1

Related Questions