How to get previous month in SQL

Posted on 2012-08-20
Last Modified: 2012-08-20
I have the code shown below that is part of my where clause.  I need to get all data for the previous calendar month, so July 1 - 31 right now since we're in August.  This statement is giving me all July data, but includes multiple years in it.  How can I fix that?

where datepart(m, BEG_DATE) = datepart(m, dateadd(m, -1, getDate()))
and datepart(y, BEG_DATE) = datepart(y, dateadd(m, -1, getDate()))

Open in new window

Question by:fcsIT
    LVL 9

    Accepted Solution

    where beg_date >= dateadd(m, datediff(m, 0, GETDATE()) - 1, 0)
       AND beg_date < dateadd(m, datediff(m, 0, GETDATE()), 0)

    Author Closing Comment


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
    Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
    Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
    Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now