tsql - How can I use a CASE condition based on a junction table in SQL Server? -


i have product table, , productrep table. products have status types.

productid statusid  tbl_product 

-

repid productid  tbl_productrep 

i'm passing status parameter stored procedure, , querying products based on that:

select * tbl_product p p.status = case when(isnull(@status, '') = '') p.status                       else @status end , p.available = 1 , p.authorizedid = @currentuserid 

as can see above, i'm defaulting whatever record if @status returns empty.

what want add "fake" status, tell procedure when want return products don't have reps assigned them. "fake" status 0.

pseudo logic

select * tbl_product p p.status = case when(isnull(@status, '') = '') p.status                       when(@status = 0) p.status                       else @status end , p.available = 1 , p.authorizedid = @currentuserid  , if @status = 0 return products don't have rep in junction table. 

how like

select * tbl_product p        (         (             p.status = case when(isnull(@status, '') = '') p.status else @status end         )         or           (             status = 0 , productid not in (select productid tbl_productrep         )     ) , p.available = 1 , p.authorizedid = @currentuserid 

this should give original result, if pass fake status, bring items not in tbl_productrep table


Comments