Wednesday, September 16, 2009

SQl Queries to find Last and First date of Current Month, Previous Month, And Next Month

Hi All,

We might have encounter at many places write quries for dates like Last and First date of Current Month, Previous Month, And Next Month. Its very common we may forget some quries which we have written earlier in time, so there is no exception for these above simple quries too.

So I have written here below to find last and first of any month. Hope this will helps at least who are new to Sql.



Declare @InputDate DATETIME

Set @InputDate = GETDATE()

First Day Of Current Month =CAST(CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' +CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01' AS DATETIME)

Last Day Of Current Month = CAST(CONVERT(VARCHAR(10),DATEADD(DD, -1, DATEADD(M, 1, CAST(YEAR(@InputDate) AS VARCHAR(4)) + '/' +CAST(MONTH(@InputDate) AS VARCHAR(2)) + '/01')),101) +' 23:59:59' AS DATETIME)

No comments:

Post a Comment