简体   繁体   中英

Conditional where clause in Select statement

I am using a stored procedure to generate a report based on parameters to SP. I have to join different where conditions depending upon parameters passed.

For ex.

ALTER PROCEDURE [dbo].[sp_Report_InventoryAging] 

@TitleFlag int=0, /*0-All veh, 1-Clear Title, 2-Without Clear Title*/

@CompName varchar(100) = 'ALL COMPANIES',

@CompBranchId varchar(50) = 'ALL',  /*All Offices*/

@StateId varchar(50)='All States'       /*All states*/ 

Select .... Where TitleFlag=@TitleFlag and

Now I want to specify conditions based on parameters like -

  1. If not 'ALL COMPANIES' then upper(Company)=upper(@CompName)
  2. If not 'ALL OFFICES' then OfficeID=@CompBranchId
  3. If not 'ALL States' then StateID=@StateID

How do I merge all of these conditions within where condition of select statement depending upon parameter value?

Any help is highly appreciated.

Do it like this:

where
(upper(Company)=upper(@CompName) or @compName = 'ALL COMPANIES')
and 
(OfficeID=@CompBranchId or @CompBranchId = 'ALL OFFICES')
and
(StateID=@StateID or @StateID = 'ALL States')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM