Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在where子句中捕获当前月份的第一个到当前日期的日期范围_Sql_Sql Server 2012 - Fatal编程技术网

Sql 在where子句中捕获当前月份的第一个到当前日期的日期范围

Sql 在where子句中捕获当前月份的第一个到当前日期的日期范围,sql,sql-server-2012,Sql,Sql Server 2012,我正在选择客户id、名称和服务日期等字段。我试图在where子句中写道,每天运行查询时,它都会捕获从当月第一天到当天的日期范围。一种方法是比较月份和年份: where year(col) = year(getdate()) and month(col) = month(getdate()) and day(col) <= day(getdate()) -- this is optional, if there is no future data (假设表中没有未

我正在选择客户id、名称和服务日期等字段。我试图在where子句中写道,每天运行查询时,它都会捕获从当月第一天到当天的日期范围。

一种方法是比较月份和年份:

where year(col) = year(getdate()) and
      month(col) = month(getdate()) and
      day(col) <= day(getdate())  -- this is optional, if there is no future data
(假设表中没有未来的数据。)

或者,更好的是:

where col >= datefromparts(year(getdate()), month(getdate()), 1)

一种方法是比较月份和年份:

where year(col) = year(getdate()) and
      month(col) = month(getdate()) and
      day(col) <= day(getdate())  -- this is optional, if there is no future data
(假设表中没有未来的数据。)

或者,更好的是:

where col >= datefromparts(year(getdate()), month(getdate()), 1)
编辑:我使用了BETWEEN来捕捉可能的未来日期/计划事件

编辑:我使用了BETWEEN来捕捉可能的未来日期/计划事件

剩下的应该很简单。提示
日期介于DATEADD(month,DATEDIFF(month,0,@mydate),0)和@mydate之间,其余的应该很简单。提示
日期添加(月,日期差异(月,0,@mydate),0)和@mydate之间的日期