TSQL - ISNULL over multiple columns

Try this:

SELECT COALESCE(LikesOranges, LikesApples, LikesPears) AS MyBit FROM FoodPreferences

This will return the first non-null value. If all fields are NULL the result is NULL.


UPDATE:

And the conclusion is:

SELECT ISNULL(COALESCE(LikesOranges, LikesApples, LikesPears),0) AS MyBit FROM FoodPreferences

so I can avoid having to write an ISNULL statement for each column,

Run this query and copy the result to your select statement. system_type_id = 104 filters the result on bit columns.

select stuff((select  ', isnull('+name+', 0)'
              from sys.columns
              where object_id = object_id('FoodPreferences') and 
                    system_type_id = 104
              for xml path('')), 1, 1, '')

Result:

-------------------------------------------------------------------------
 isnull(LikesOranges, 0), isnull(LikesApples, 0), isnull(LikesPears, 0)

I don't think so. But an option might be to create a view onto that table and put all the ISNULL statements in the view. At least then you won't have to do it every time

eg.

CREATE VIEW vwFoodPreferences
AS
SELECT Name, 
       Age, 
       ISNULL(LikesOranges,0) AS LikesOranges, 
       ISNULL(LikesApples,0) AS LikesApples, 
       ISNULL(LikesPears,0) AS LikesPears
FROM   FoodPreferences