How can I select the first day of a month in SQL?
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))
+ '/' + CAST(MONTH(@mydate) AS VARCHAR(2)) + '/01' AS DATETIME)
but this is not very elegant, and probably not very fast either.
Is there a 'better way to do this ? (I'm using SQL Server 2008)
SELECT DATEADD(month, DATEDIFF(month, 0, @mydate), 0) AS StartOfMonth
除了上述所有答案之外,还有一种基于sql 2012
引入的函数的方法
SELECT DATEFROMPARTS(YEAR(@mydate),MONTH(@mydate),1)
SQL Server 2008:
SELECT DATEADD(DAY,1,EOMONTH(@mydate,-1))
链接地址: http://www.djcxy.com/p/94366.html
上一篇: 如何只保留日期时间值(SQL Server)的时间部分?
下一篇: 我怎样才能在SQL中选择一个月的第一天?