I just need to select the first day of the month of a given DateTime variable.

I know it’s quite easy to do using this kind of code:

select CAST(CAST(YEAR(@mydate) AS VARCHAR(4)) 
+ "https://stackoverflow.com/" + CAST(MONTH(@mydate) AS VARCHAR(2)) + '/01' AS DATETIME)

But unfortunately, this is not very elegant, and not very fast either.

Is there a better way to do this? I’m using SQL Server 2008.

33 Answers
33

SELECT DATEADD(month, DATEDIFF(month, 0, @mydate), 0) AS StartOfMonth

Leave a Reply

Your email address will not be published. Required fields are marked *