Get First Day and Last Day of Month – SQL Server

One of the features i love about SQL Server is function supports. Divide your task in functions just like other programming language. In this article i am going to show you that how to display the First Day and Last Day of Month in SQL Server.

Create a below function to get the First Day of Month:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION GetFirstDay
(
-- Add the parameters for the function here
@InputDate DateTime
)
RETURNS DateTime
AS
BEGIN
-- Declare the return variable here
DECLARE @Result DateTime

-- Add the T-SQL statements to compute the return value here
SELECT @Result = CAST(CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' + CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01' AS DATETIME)

-- Return the result of the function
RETURN @Result

END
GO

Now, Create Below Function to get the Last day of month.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION GetLastDay
(
-- Add the parameters for the function here
@InputDate DateTime
)
RETURNS DateTime
AS
BEGIN
-- Declare the return variable here
DECLARE @Result DateTime

-- Add the T-SQL statements to compute the return value here
SELECT @Result = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@InputDate)+1,0))

-- Return the result of the function
RETURN @Result

END
GO

To get the values from function, run below script

select dbo.GetFirstDay(GETDATE()) as StartDate
select dbo.GetLastDay(GETDATE()) as EndDate

remember that to call function we have to call like dbo.functionName

Posted

in

,

by

Tags:


Related Posts

Comments

One response to “Get First Day and Last Day of Month – SQL Server”

  1. Hi end swim spas Avatar
    Hi end swim spas

    i want to convert the date into the same format of getdate() to have comparision with the date passed from front.? how can i do that..?


    Hi end swim spas

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading