SQL where子句中的布尔条件

时间:2017-11-03 06:44:25

标签: sql-server booleanquery

我想编写一个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 <> ''))

现在我也希望纳入所有条件,任何人都可以建议我如何实现

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

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')

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

答案 3 :(得分:0)

它应该满足你的要求。

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'))