我认为有两种可能的方法:
(1) Store 子串日期,例如:
'2013' -- year 2013
'2013-01' -- year 2013, January
'2013-01-01' -- year 2013, January 1
(2) Store 3个不同的列,年,月,日(并且您可以毫无问题地建立索引年+月+日)
2013 null null -- year 2013
2013 1 null -- year 2013, January
2013 1 1 -- year 2013, January 1st
哪一种最好取决于您想要如何查询数据。假设您有存储过程并且想要传递一个参数以使所有行都符合条件。
In case (1),你传递字符串@Date = '2013-01'
作为参数,您想要获取年份 = 2013 和月份 = 01 的所有行。因此where
子句就像:
where left(Date, len(@Date)) = @Date
In case (2),您传递三个参数 -@Year = 2013, @Month = 1, @Day = null
和where
子句类似于:
where
Year = @Year and -- Supposing @Year is always not null
(@Month is null or @Month is not null and Month = @Month) and
(@Day is null or @Day is not null and Day = @Day)
它可能会更复杂,具体取决于您想要如何处理行。例如,如果您给出如下参数2013-01
,您是否想要获取 Month = null 的行?
另一方面,如果您想传递日期并检查它是否属于日期范围,那么 Gordon Linoff 建议是一个不错的选择。