How can I select the first day of a month in SQL?(如何在 SQL 中选择一个月的第一天?)
问题描述
我只需要选择给定 DateTime 变量的月份的第一天.
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 unfortunately, this is not very elegant, and not very fast either.
有没有更好的方法来做到这一点?我使用的是 SQL Server 2008.
Is there a better way to do this? I'm using SQL Server 2008.
推荐答案
除了以上所有答案,还有一种基于 sql 2012
In addition to all the above answer, a way based on a function introduced in sql 2012
SELECT DATEFROMPARTS(YEAR(@mydate),MONTH(@mydate),1)
这篇关于如何在 SQL 中选择一个月的第一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL 中选择一个月的第一天?
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
