【发布时间】:2015-02-18 16:17:15
【问题描述】:
我在 SQL Server 中有一个表,它有很多行,有一个 created_date 列。此列包含从 2006 年开始的行。
我想获取在 2015 年 2 月及之前创建的所有行。此存储过程有一个参数 @month。它应该根据输入的@month 值选择所有行。
这是我的查询:
select *
from products
where 1=1
and year(created_date) <= 2015
and month(created_date) <= @month
但此查询仅返回在往年 2 月 月及之前创建的记录不包括 在 2014 年其他月份创建的记录(例如 2014- 03-17, 2014-05-05 除外)。
我必须根据输入的@month 获得一个新日期。假设我进入了 7 月,我想要条件“where created_date
所以我改变了我的查询,
declare @date datetime
set @date = CAST((2015 + '-' + @month + '-' + 28) as datetime)
select *
from products
where 1=1
and year(created_date) <= 2015
但是这个查询返回 1905-08-08 00:00:00.000 我想得到 2015-02-28 00:00:00.000 而且我必须根据输入的@month 找到总天数,这样我可以将该数字传递给 CAST((2015 + '-' + @month + '-' + 28) as datetime) 而不是 28。
【问题讨论】:
-
只使用具有您想要的限制值的日期变量作为标准,而不是使用 year() 和 month() 函数?例如。 created_date
标签: sql-server