Learn how to a build a cloud-first strategyRegister Now


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

Posted on 2011-05-09
Medium Priority
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 41

Expert Comment

ID: 35724767
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 52

Accepted Solution

_agx_ earned 2000 total points
ID: 35724775

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

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

810 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