Reputation: 65
I have a filter for the clients for a report, if the person put the filter Client it uses,else it ignores and bring all clients. This is my Where clause.
Where [S].ano_mes = @ano_mes OR @ano_mes IS NULL
AND S.cnpj = @cnpj or @cnpj is null
AND S.cod_produto = @cod_produto or @cod_produto is null
AND CASE WHEN (len(@cnpj) > 0) THEN
(S.CGC_Cliente +''-''+S.Seq_Cliente) in(SELECT cnpjseq FROM #Tb_CliSelecionados)
END
The problem is in the CASE WHEN part,the rest works.
If the variable @cnpj has value THEN it should use the filter.
The filters is CGC_CLIENTE and SEQ_CLIENTE together.
The table #Tb_CliSelecionados has the parameters Concatenated equals,exemple,both the table with alias S and #Tb_CliSelecionados has '060746948041730-00'
i'm getting erro in two parts in the "IN" its says incorrect syntax near "IN" And in the END saying incorrect syntax near "END".Expection ")"
Someone knows what i'm doing wrong in the case when part?
Upvotes: 1
Views: 851
Reputation: 3756
The CASE WHEN
clause is incorrect. It should look like:
AND CASE
WHEN @cnpj IS NULL
THEN 1
WHEN (len(@cnpj) = 0)
THEN 1
WHEN (S.CGC_Cliente +''-''+S.Seq_Cliente) in (SELECT cnpjseq FROM #Tb_CliSelecionados
THEN 1
ELSE 0
END = 1
Upvotes: 1
Reputation: 48197
CASE
return one expresion isn't a flow control.
AND CASE WHEN len(@cnpj) IS NULL
THEN 1
WHEN (len(@cnpj) > 0)
THEN CASE WHEN exists
(SELECT 1
FROM #Tb_CliSelecionados
WHERE cnpjseq = S.CGC_Cliente +''-''+ S.Seq_Cliente )
THEN 1 -- if exist the match return the row
ELSE 0 -- other wise ignore the row
END
ELSE 1 -- if len(@cnpj) == 0 then return all rows
END = 1 -- HERE YOU return the row if CASE return 1
Upvotes: 1
Reputation: 77896
You can change that part to
AND ( len(@cnpj) > 0
AND S.CGC_Cliente + '-' + S.Seq_Cliente in (SELECT cnpjseq FROM #Tb_CliSelecionados))
Upvotes: 0