Reputation: 5044
I wanted to write an sql query to fetch data as:
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.
i tried below query for yes and no
declare @invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((@invoiced = 'yes') or (InvoiceNumber = ''))
and
((@invoiced = 'no') or (InvoiceNumber <> ''))
now i also want to incorporate all condition, could anyone suggest how could i achieve that
Upvotes: 0
Views: 151
Reputation: 471
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')
Please update this query with above query.
Upvotes: 0
Reputation: 5962
It should fulfill your requirement.
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'))
Upvotes: 0
Reputation: 36
declare @invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
@invoiced = 'all'
OR
(@invoiced = 'yes' AND InvoiceNumber <> '')
OR
(@invoiced = 'no' AND InvoiceNumber = '')
Upvotes: 2
Reputation: 8033
Try this
declare @invoiced as nvarchar(10) = 'no'
select
*
from OrderSummary
where
(
@invoiced = 'all'
OR
(
@invoiced = 'yes'
AND
InvoiceNumber <> ''
)
OR
(
@invoiced = 'no'
AND
InvoiceNumber = ''
)
)
Upvotes: 0