Sql 如何选择2个布尔列并检索1个布尔结果(两者都必须为true=true)
在SQL Server中,我有多个Sql 如何选择2个布尔列并检索1个布尔结果(两者都必须为true=true),sql,sql-server-2008,Sql,Sql Server 2008,在SQL Server中,我有多个bit列。如果product=False或Category=False,我想返回False 我的测试代码: declare @b0 bit declare @b1 bit set @b0 = 0 set @b1 = 1 select (@b0 and @b1) select (@b0 + @b1) select (@b0 = @b1) 但所有3个选择都崩溃了 我的实际代码片段: select c.bCatActive, -- I want
bit
列。如果product=False或Category=False,我想返回False
我的测试代码:
declare @b0 bit
declare @b1 bit
set @b0 = 0
set @b1 = 1
select (@b0 and @b1)
select (@b0 + @b1)
select (@b0 = @b1)
但所有3个选择都崩溃了
我的实际代码片段:
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
当然,我可以用两个If-then来实现这一点,但我当前的查询是一个干净的查询,所以我希望用一行简洁的语句来实现这一点。那么显式比较呢
(case when c.bCatActive = 1 and p.bProdActive = 1 then 1 else 0 end) as IsActive
位
不是布尔值
您还应该学习正确的、明确的、标准的、可读的
JOIN
语法。如果只有0和1,请尝试以下方法:
select (c.bCatActive * p.bProdActive) as IsActive
from Category c
, Product p
where p.ProductID = 999
and c.CategoryID = p.CategoryID
如果c.bCatActive和p.bProdActive的值均为1,则它将仅生成1作为IsActive。如果其中任何一个为0,则返回0。这是我现在唯一能想到的选择,因为你不想使用if或case。你非常接近,布尔逻辑应该使用布尔逻辑:
declare @b0 bit
declare @b1 bit
set @b0 = 0
set @b1 = 0
select (@b0 & @b1)
将&用于和,|用于或这些字段中是否有一个可以为空?-在ANSI-92 SQL标准(大约30年前)中,旧样式的逗号分隔表列表样式被正确的ANSI
JOIN
语法所取代,它的使用是不鼓励的:如果两个字段一起有效地定义了四种不同的状态,那么它们作为一个单独的tinyint
或char
加上一个复选框可能会更好谢谢!“布尔逻辑应该使用布尔逻辑”和
是布尔逻辑,但位
不是布尔逻辑,而是1位整数<代码>&是位操作,您可以对整数进行位操作。所以更准确地说“bit
是一个整数,应该使用位操作。”