【问题标题】:How to select 2 boolean columns and retrieve 1 boolean result (both must be true = true)如何选择 2 个布尔列并检索 1 个布尔结果(两者都必须为 true = true)
【发布时间】:2021-06-05 19:18:48
【问题描述】:

在 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 个选择都崩溃了。

我的实际代码sn-p:

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-Thens 来做到这一点,但是我当前的查询是一个干净的查询,所以我希望能在一行中做到这一点。

【问题讨论】:

  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(差不多 30 年前),不鼓励使用它
  • 好奇:如果这两个字段一起有效地定义了四个独立的状态,那么它们可能会更好地作为带有检查约束的单个 tinyintchar

标签: sql sql-server-2008


【解决方案1】:

显式比较怎么样?

(case when c.bCatActive = 1 and p.bProdActive = 1 then 1 else 0 end) as IsActive

bits 不是 布尔值

您还应该学习正确、明确、标准、可读的JOIN 语法。

【讨论】:

    【解决方案2】:

    如果它们只是 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。

    【讨论】:

    • 这些字段中的任何一个都可以为空吗?
    【解决方案3】:

    你很接近,布尔值应该使用布尔逻辑:

    declare @b0 bit
    declare @b1 bit
    
    set @b0 = 0
    set @b1 = 0
    
    select (@b0 & @b1)
    

    使用 & 表示和,| 表示或

    【讨论】:

    • 谢谢!我真的就那么接近。
    • "布尔值应该使用布尔逻辑" and 是布尔逻辑,但bit 不是布尔值,它是一个 1 位整数。 & 是位操作,您可以使用整数进行操作。所以更准确地说“bit 是一个整数,应该使用位操作。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多