Skip to content
Advertisement

How to select 2 boolean columns and retrieve 1 boolean result (both must be true = true)

In SQL Server I have multiple bit columns. If either the product = False or the Category = False, I want to return False.

My test code:

declare @b0 bit
declare @b1 bit

set @b0 = 0
set @b1 = 1

select (@b0 and @b1)
select (@b0 + @b1)
select (@b0 = @b1)

But all 3 selects crash.

My actual code snippet:

select 
    c.bCatActive,    -- I want to dispose of this line.
    p.bProdActive,   -- I want to dispose of this line.
    (c.bCatActive and p.bProdActive) as IsActive  -- I want to retrieve this line but doesn't work.
from 
    Category c, Product p
where 
    p.ProductID = 999
    and c.CategoryID = p.CategoryID

Of course I can do this with two If-Thens but my current query is pleasantly one clean query so I was hoping to do this in one neat line.

Advertisement

Answer

You are very close, booleans should use boolean logic:

declare @b0 bit
declare @b1 bit

set @b0 = 0
set @b1 = 0

select (@b0 & @b1)

Use & for and, | for or

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement