SQL:DATEDIFF如果开始日期大于另一个字段中的日期

时间:2016-10-28 10:01:05

标签: sql sql-server if-statement sql-server-2012 datediff

我正在寻找我已声明为变量的两个日期之间的区别

DECLARE @start_date DATETIME
SET @start_date= '20000728'

DECLARE @end_date DATETIME
SET @end_date= '20161028'

但仅当@start_date大于DATE_CREATED时。如果不是,我想区分DATE_CREATED和@end_date

我该怎么做呢?

目前我只有:

DATEDIFF(DAY, @start_date, @end_date) AS 'DAYS_AVAIL_RANGE'

我不确定如何使用IF语句来执行此操作,

欢迎任何帮助,欢呼!

3 个答案:

答案 0 :(得分:1)

试试这个。这肯定会解决您的问题,因为此处为日期/时间值执行了转换。

select
    case when DATEDIFF(day,convert(date,DATE_CREATED),CONVERT(date,@start_date)) > 0
        then datediff(DAY, convert(date,@start_date), convert(date,@end_date))
    else
        datediff(DAY, convert(date,DATE_CREATED), convert(date,@end_date)) 
    end

答案 1 :(得分:0)

您想要case

select (case when @start_date > date_created
             then datediff(DAY, @start_date, @end_date) 
             else datediff(DAY, date_created, @end_date) 
        end) as days_avail_range

答案 2 :(得分:0)

试试这个

 select datediff(DAY, (select max(v) from (VALUES (@start_date), (DATE_CREATED)) as value(v)) , @end_date) from yourtable