Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a computed column on a datetime

I have a nullable DateTime column in my SQL Server 2005 table called DateTimeDeleted.

I'd like to have a BIT type computed column that is 1 if DateTimeDeleted is not null, otherwise 0. However, I can't seem to get the syntax for the formula correct.

I've tried:

(TsDeleted IS NULL) = 0

but it gives me a syntax error.

Help! :)

like image 775
Craig Shearer Avatar asked Sep 09 '26 14:09

Craig Shearer


2 Answers

Alter Table MyTableName 
  Add IsDeleted As 
     (Case When [DateTimeDeleted] Is Null 
       Then (0) Else (1) End)

This will output as an integer... If you really want it to be a bit, then:

Alter Table MyTableName 
  Add IsDeleted As 
     cast( (Case When [DateTimeDeleted] Is Null 
       Then (0) Else (1) End) as Bit)
like image 193
Charles Bretana Avatar answered Sep 12 '26 03:09

Charles Bretana


I think this should work:

update table
set IsDeleted = case when DateTimeDeleted is null then 0 else 1 end
like image 21
Jon Avatar answered Sep 12 '26 04:09

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!