Usually for case-based aggregation you convert pseudo
select 1 AS A IF @b!=-1 then union all select 2 as B END IF
in
select 1 AS A union all select 2 as B WHERE @b!=-1
At your request it will be
SELECT [ID_ADRESS],[ID_ENT],[VOI_ADRESS],[NUM_ADRESS],[BTE_ADRESS] ,[CP_ADRESS],[VIL_ADRESS] FROM [ADRESSES] WHERE ( (VIL_ADRESS != 'NC' AND VIL_ADRESS != '--') AND (@OnlyLinked = 0 OR ID_ENT is not null) ) UNION SELECT [ID_ADRESS],[ID_ENT],[VOI_ADRESS],[NUM_ADRESS],[BTE_ADRESS] ,[CP_ADRESS],[VIL_ADRESS] FROM [ADRESSES] WHERE ID_ADRESS = @ObligedId AND (@ObligedId != -1)
However, since in this particular query the data from the same table uses only different filters, you should use OR filters instead. Note: if you used UNION ALL, it cannot be reduced this way because of possible duplicates that UNION ALL saves. For UNION (which removes duplicates anyway), OR shorthand works just fine
SELECT [ID_ADRESS],[ID_ENT],[VOI_ADRESS],[NUM_ADRESS],[BTE_ADRESS] ,[CP_ADRESS],[VIL_ADRESS] FROM [ADRESSES] WHERE ( (VIL_ADRESS != 'NC' AND VIL_ADRESS != '--') AND (@OnlyLinked = 0 OR ID_ENT is not null) ) OR ( ID_ADRESS = @ObligedId AND (@ObligedId != -1)
RichardTheKiwi
source share