Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I force the data type of a computed column to a bit field that don't allow nulls?

I got a computed column that I need to be a bit field, here an example of formula :

case when ([some_field] < [Some_Other_field]) 
then 0 
else 1 
end

The data type of computed column set using this formula is int.

What's the best way to force the correct data type?

With a CONVERT statement on the whole case, data type is bit but it Allow Nulls

CONVERT([bit], 
        case when (([some_field] < [Some_Other_field]) 
        then 0 
        else 1 
        end,
        0)

Same thing with a CONVERT statement on the result expressions, data type is bit but it Allow Nulls

case when (([some_field] < [Some_Other_field]) 
then CONVERT([bit], (0), 0) 
else CONVERT([bit], (1), 0) 
end

Or there is a smarter way of doing this?

like image 839
DavRob60 Avatar asked Aug 30 '11 13:08

DavRob60


2 Answers

If you persist the computed column you can specify not null. http://msdn.microsoft.com/en-us/library/ms186241.aspx

CONVERT([bit], 
        case when (([some_field] < [Some_Other_field]) 
        then 0 
        else 1 
        end,
        0) PERSISTED NOT NULL
like image 152
Mikael Eriksson Avatar answered Oct 24 '22 04:10

Mikael Eriksson


Wrap the computed column definition in ISNULL, with whatever you like as the second argument (provided it's a bit, or convertible to such).

This is one of the few places where you have to use ISNULL rather than (the generally better designed) COALESCE. SQL Server has special case logic to realise that an ISNULL with a non-null second argument represents a non-nullable result.

E.g.:

ISNULL(CONVERT(bit,case when ([some_field] < [Some_Other_field]) 
then 0 
else 1 
end),0)

This can also be used in e.g. view definitions.

like image 23
Damien_The_Unbeliever Avatar answered Oct 24 '22 02:10

Damien_The_Unbeliever