Using case in null field

Asked

Viewed 490 times

3

I have the following structure tb_boletim:

|Cod|boletim|dt_enviado|
| 1 |  N    | NULL     |
| 2 |  S    |24/08/2018|
| 3 |  S    | NULL     |
| 4 |  S    |23/08/2018|
| 5 |  S    |23/08/2018|
| 6 |  S    | NULL     |
| 7 |  N    | NULL     |
| 8 |  N    | NULL     |

I want to make ONLY one sql that brings me in two ways, depending on parameter passed to the field "newsletter".

I can make a Where case like this?

select * from tb_boletim where
boletim = 'S' and
case
 when boletim = 'S' then dt_enviado is not null
 when boletim = 'N' then dt_enviado null
end

Expected result:

|Cod|boletim|dt_enviado|
| 2 |  S    |24/08/2018|
| 4 |  S    |23/08/2018|
| 5 |  S    |23/08/2018|

or

|Cod|boletim|dt_enviado|
| 1 |  N    | NULL     |
| 7 |  N    | NULL     |
| 8 |  N    | NULL     |   

2 answers

3


Yes, you can.
The parameter received (@parametro_boletim) will control whether the validation will be done with it equal to S or the N):

SELECT * 
FROM tb_boletim 
WHERE boletim = @parametro_boletim
  ((boletim = 'S' and dt_enviado is not null) OR
   (boletim = 'N' and dt_enviado null))

3

I’m not sure I fully understood the question...

Is this what you want?


select 
   Cod
  ,boletim
  ,case when boletim='S' then dt_enviado else NULL END dt_enviado 
FROM tb_boletim

/*WHERE BOLETIM='S'*/
/*WHERE BOLETIM='N'*/

You can add a WHERE clause to filter or not according to the BOLETIM field

Browser other questions tagged

You are not signed in. Login or sign up in order to post.