Date Constraint

  • Hello,

    I need a Check Constraint on a date field (smalldatetime) that will check for a date range between the current date (GETDATE()) and two years into the future.

    How would I express such a constraint?

    Thanks for your help!

    CSDunn

  • If by "the current date" you mean including the current time, then just:

    
    
    CHECK (ColumnName BETWEEN GETDATE() AND DATEADD(yy,2,GETDATE()))

    Otherwise, perhaps something like this:

    
    
    CHECK (ColName >= CONVERT(char(8),GETDATE(),112)
    AND ColName < DATEADD(yy,2,CONVERT(char(8),GETDATE(),112))+1)

    --Jonathan



    --Jonathan

  • Something like this might work:

    ALTER TABLE tablename

    ADD datefield DATETIME CHECK

    (datefield > GETDATE() AND datefield < GETDATE()+730)

    -SQLBill

  • Oooo, Jonathan beat me to the answer. Must have been just by a second or two. (BTW-his suggestion is better than mine).

    -SQLBill

  • Thanks for your help!

    CSDunn

  • I would like to point out that Jonathan is converting to the ISO date format which is better than other date formats as it is not likely to fail when compared. Good job.

Viewing 6 posts - 1 through 5 (of 5 total)

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