Get the First and Last date of the Previous Month IN MS SQL

Step 1
First we create a user defined function GetFirstDate function,it is look like this

CREATE FUNCTION dbo.GetFirstDate(@OriginalDate datetime)
RETURNS varchar(50)
AS
    BEGIN
            
            DECLARE @FirstDate datetime
            
            SET @FirstDate=DATEADD(MONTH,-1,DATEADD(DAY,-DATEPART(Day,@OriginalDate)+1, @OriginalDate))
            
            RETURN Convert(varchar(50),@FirstDate,101)
    END

In this function we get first date of the previous month from given actual date value.

Step 2
Create a user defined function GetLastDate function,it is look like this


CREATE FUNCTION dbo.GetLastDate(@OriginalDate datetime) 
RETURNS varchar(50)
AS
    BEGIN
        DECLARE @LastDate datetime
        
        SET @LastDate=DATEADD(DAY,-DATEPART(DAY,@OriginalDate), @OriginalDate)
        
        RETURN Convert(varchar(50),@LastDate,101)
    END
In this function we get last date of the previous month from given actual date value.

Step 3
Call above user defined functions,it is look like this
--Date value must specify on this format ---  MM/DD/YYYY
    SELECT dbo.GetFirstDate('01/18/2010') as 'FirstDate of the Previous Month',
               dbo.GetLastDate('01/18/2010') as 'LastDate of the Previous Month'


Output

Comments

Popular posts from this blog

GROUP BY, CUBE, ROLLUP and SQL SERVER 2005

How to get content of Ckeditor & Fckeditor using Javascript

How to Fix Error- Sys.WebForms.PageRequestManagerTimeoutException - The server request timed out