views:

52

answers:

2

I'd like to have two columns in a database, one for tracking whether or not the user has submitted something, and another for the timestamp of that submission.

How can I structure the table definition so that the state of these two columns is never inconsistent?

Basically, I'd like the boolean field to be driven by whether or not a SubmittedDate column is null. Here's a snippet of the table definition:

CREATE TABLE SomeSchema.SomeTable 
(
    ...
    SubmittedDate                   datetime                NULL,
    Submitted                       bit                     NOT NULL        DEFAULT(0), -- Drive off of SubmittedDate?
    ...

)

What's the best way to accomplish this?

Thanks!

+6  A: 

Use only one column - the DATETIME one. It serves double duty - the column being null means it wasn't submitted, but if the value exists - you also know when.

OMG Ponies
+1 @OMG Ponies - I totally agree and I had some discussion previously as to what was the better practice. I was just curious as to the actual syntax of setting up the column, but you're absolutely right that it serves double duty.
Brandon Linton
+2  A: 

Use a computed column:

CREATE TABLE SomeSchema.SomeTable 
(
    ...
    SubmittedDate                   datetime                NULL,
    Submitted      as cast(case when SubmittedDate is null then 0 else 1 end as bit)
)
Remus Rusanu
Great, syntax worked perfectly. Thanks!
Brandon Linton