SQL where 子句中的布尔条件

Boolean conditions in SQL where clause

我想编写一个 sql 查询来获取数据:

1. when param = 'all' it should list data across the table
2. when param = 'yes' it should list data where invoicenumber is not empty.
3. when param = 'no' it should list data where invoicenumber is empty.

我尝试在下面查询是和否

declare @invoiced as nvarchar(10) = 'no'
select * from OrderSummary 
    where 
((@invoiced = 'yes') or (InvoiceNumber = ''))
    and
((@invoiced = 'no') or (InvoiceNumber <> ''))

现在我也想合并所有条件,有人可以建议我如何实现吗

declare @invoiced as nvarchar(10) = 'no'
select * from OrderSummary 
    where 
    @invoiced = 'all'
    OR 
    (@invoiced = 'yes' AND InvoiceNumber <> '')
    OR 
    (@invoiced = 'no' AND InvoiceNumber = '')

试试这个

declare @invoiced as nvarchar(10) = 'no'
select 
  * 
  from OrderSummary 
  where 
  (
     @invoiced = 'all'
     OR
     (
        @invoiced = 'yes'
        AND
        InvoiceNumber <> ''
     )
     OR
     (
        @invoiced = 'no'
        AND
        InvoiceNumber = ''
     )
  )
declare @invoiced as nvarchar(10) = 'no'
select * from OrderSummary 
    where 
((@invoiced = 'yes') and (InvoiceNumber <> '') )
    or
((@invoiced = 'no') and ( (InvoiceNumber = '') or (InvoiceNumber = null)))
or (@invoiced = 'all')

请使用上述查询更新此查询。

应该能满足你的要求。

declare @invoiced as nvarchar(10) = 'no'

select * from OrderSummary 
    where
((@invoiced in ('all','no')) OR (@invoiced = 'yes' AND InvoiceNumber  <> ''))
    and
((@invoiced in ('all','yes')) OR (@invoiced = 'no' AND InvoiceNumber  = ''))
    and
(@invoiced in ('no','yes'))