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?
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
ISNULLrather than (the generally better designed)COALESCE. SQL Server has special case logic to realise that anISNULLwith a non-null second argument represents a non-nullable result.E.g.:
This can also be used in e.g. view definitions.