sql server 2005 - How to use case when in where conditon tsql? -


following part of stored procedure:-

@id int @col1 int @col2 int  select *  table_01 t1 join table_02 t2 on t1.col = t2.col    1 = case when @col1 = 0 1 else (case when t2.col1 = @col1 1 else 0 end) end   , 1 = case when @col2 = 0 1 else (case when t2.col2 = @col2 1 else 0 end) end   , 1 = case when @id = 0 1 else (case when t2.id = @id 1 else 0 end) end 

currently

  • if @id = 0 ignores condition
  • if @id has value returns results based on criteria satisfaction

i need add condition there :-

if @id = -1 should not return result (coz there no match) should act @id = 0 (ignore add expresssion)

am clear? :(

select ... table_01 t1     join table_02 t2          on t1.col = t2.col case          when @id = 0 1          when t2.id = @id 1          when @id = -1 0         else 0          end = 1 

if last condition should trump other two, need change order:

select ... table_01 t1     join table_02 t2          on t1.col = t2.col case          when @id = -1 0         when @id = 0 1          when @id = t2.id 1          else 0          end = 1 

of course way may perform better (assuming @id = -1 trumps):

select ... table_01 t1     join table_02 t2          on t1.col = t2.col @id != -1      , ( @id = 0 or @id = t2.id ) 

update based on edit of op

it sounds trying following:

select ... table_01 t1     join table_02 t2          on t1.col = t2.col @id != -1     , ( @col1 = 0 or @col1 = t2.col1 )     , ( @col2 = 0 or @col2 = t2.col2 )     , ( @id = 0 or @id = t2.id ) 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -