如果列(日,月和年)在SQL Server中单独存储,请比较日期

时间:2018-05-29 08:41:40

标签: sql sql-server sql-server-2008

我有3列DayMonthYear类型INT完全独立。我需要的是将日期(格式:yyyy-mm-dd)传递给WHERE子句以检查以下日期是否匹配。处理这个问题的最佳方法是什么?

4 个答案:

答案 0 :(得分:5)

2012年它将是DateFromParts(Year,Month,Day),但你已经标记了2008年,这意味着我们必须回归旧的技巧。

dateadd(mm, (@YourYearValue - 1900) * 12 + @YourMonthValue- 1 , @YourDayValue - 1)

将3个整数放入其中(通过联接中的列或适当的参数),并且您有一个可以使用的日期。

SQL小提琴:http://www.sqlfiddle.com/#!18/9eecb/19988

答案 1 :(得分:0)

对于SQL Server 2008

    declare @Day int = 29, @Month int = 5, @Year int = 2018

    select t.*
    from [table] t
    where t.[Date] = cast(cast(@Year as char(4))+ '-' + cast(@Month as char(2)) + '-' + cast(@Day as char(2)) as date)

仅适用于2012及以后使用DATEFROMPARTS:

where t.[Date] = DATEFROMPARTS(@Year, @Month, @Day)

答案 2 :(得分:0)

也许这个解决方案:

where cast(cast(@yyyy as varchar(4))+'-'+cast(@mm as varchar(2))+'-'+cast(@dd as 
varchar(2)) as date) ...

并用你的字段替换@ yyyy,@ mm,@ dd

答案 3 :(得分:0)

我建议以下内容,我们可以使用SQL函数从完整日期开始参与,而不是使用分隔值创建日期,并相应地进行比较,我认为这是比较的最佳方式

n <- 5
p <- 2
animals <- c(rep("dog",n),rep("cat",p))