To get dates starting from the previous month based on current system time, you will use DATEADD()
and GETDATE()
.
DATEADD
returns a specified date with the specified number interval
(signed integer) added to a specified datepart of that date.
DATEADD (datepart , number , date )
GETDATE
returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
GETDATE ( )
To calculate the dates that match from the start of last month (remember, this is an example and may need modification with your code):
SELECT [col1], [col2], [dt] FROM [table]
WHERE [dt] >= convert(varchar,DATEADD(MONTH,-1,
DATEADD(MONTH,DATEDIFF(MONTH,0,
getdate()),0)),101)
Please do some reading about DATEDIFF()
as well, and CONVERT()
to understand how the formatting represented by 101
works. You may prefer 121
instead.
(Additional source: Terry Apodaca’s article,
“SQL Dates – First, Current, Last Day of Month”, which moved
from this old address
to http://v1.terryapodaca.com/2008/01/28/sql-dates-first-current-last-day-of-month
(or you can read an archived copy at the Wayback Machine).)
You have more than one question here. Please modify the question for the first part, and post the second part as a separate question, if the answer below does not satisfy your query. – None – 2012-08-14T01:09:33.967