Maximum date in query

  • What would be the best way to get the maximum date, comparing 2 different date fields where either could be null in a Select statement?

     

    I've been trying something like the following, but doesn't work with @d2 set to null:

    declare @bigd datetime

    declare @d1 datetime

    declare @d2 datetime

    set @d1 = cast('12/20/2001' as datetime)

    set @d2 = cast('12/21/2001' as datetime)

    select @bigd = CASE WHEN @d1 > @d2 THEN @d1 ELSE @d2 END

    print @bigd

  • try this

     

    declare @bigd datetime

    declare @d1 datetime

    declare @d2 datetime

    declare @dc varchar(8)

    declare @d2c varchar(8)

    set @dc = null

    set @d2c = '1/1/2005'

    set @d1 = cast( case

              when @dc IS Null THEN  '1/1/3900'

        WHEN @dc = '' THEN  getdate()

       ELSE @dc END as datetime)

    set @d2 = cast( case

              when @d2c IS Null THEN  '1/1/3900'

        WHEN @d2c = '' THEN  getdate()

       ELSE @d2c END as datetime)

    select @bigd = CASE WHEN @d1 > @d2 THEN @d1 ELSE @d2 END

    print @bigd

  • select

    CASE WHEN @d1 > ISNULL(@d2,'1753-1-1') THEN @d1 ELSE @d2 END

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply