Search code examples
sqlsql-servert-sqlsql-server-2008datetime

How can I select the first day of a month in SQL?


How can one 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)) 
+ '/' + CAST(MONTH(@mydate) AS VARCHAR(2)) + '/01' AS DATETIME)

This is not very elegant, and not very fast either.

Is there a better way to do this?


Solution

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