在SQL中如何选择一个月的第一天? [英] How can I select the first day of a month in SQL?

查看:83
本文介绍了在SQL中如何选择一个月的第一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要选择一个给定datetime变量的月份的第一天。

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

我知道使用这种代码很容易: p>

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.

有没有更好的方法来做到这一点? (我使用SQL Server 2008)

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中如何选择一个月的第一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆