sql code to change the given date to the last day of the previous month

Posted on 2011-05-09
Last Modified: 2012-05-11
  Hi ,

    I need to check in my SQL stored procedure , if the input date is 3 months before now
    then set it to last day of the previous month of the given date.
    Ex: if the input date parameter is 02/12/2010,  i need to set it to 01/31/2010
   Can you please help me how o check the input date, if it is 3 months before now
   and how to set it to the previous month last day of the given input date.

Question by:ram27
    LVL 40

    Expert Comment

    Check this/
    declare @date datetime
    set @date = '02/12/2010'
    select case when DATEDIFF(MONTH,@date,GETDATE()) >3 
                then DATEADD(dd,-1,CONVERT(datetime,CONVERT(varchar(6),@date,112)+'01'))
                else @date end -- 2010-01-31 00:00:00.000

    Open in new window

    LVL 51

    Accepted Solution


    declare @inputDate datetime
    set @inputDate = '2011-02-12'
    if dateDiff(m, @inputDate, getDate()) >= 3
    	set @inputDate = dateAdd(d, -1, convert(datetime, convert(varchar(6), @inputDate, 112) +'01', 112))
    select @inputDate

    Open in new window


    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Introduction In my previous article ( I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
    Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
    Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
    This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

    746 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

    16 Experts available now in Live!

    Get 1:1 Help Now