我认为有两种可能的方法:
(1)存储日期的子串,如:
'2013' -- year 2013
'2013-01' -- year 2013, January
'2013-01-01' -- year 2013, January 1
(2)存储3 个不同的列,年、月、日(您可以毫无问题地构建索引年 + 月 + 日)
2013 null null -- year 2013
2013 1 null -- year 2013, January
2013 1 1 -- year 2013, January 1st
哪个最好取决于您要如何查询数据。假设您有存储过程,并且您想传递一个参数以使所有行都符合条件。
在情况(1)中,您将字符串@Date = '2013-01'
作为参数传递,并且您希望获取 year = 2013 和 month = 01 的所有行。因此该where
子句将如下所示:
where left(Date, len(@Date)) = @Date
在情况(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)
它可能更复杂,具体取决于您要如何处理行。例如,如果您提供参数 like 2013-01
,您是否想要获取月份 = null 的行?
另一方面,如果您想传递日期并检查它是否属于日期范围,那么 Gordon Linoff 建议是一个不错的选择。