How not to bring a particular column in SQL using IF and ELSE?

Asked

Viewed 743 times

2

Gentlemen, I have a table where I want to bring the column when the value is null but when it is filled it should not be displayed, as I can implement this condition in SQL ?

SELECT 
    OBS.NUOBS,
    OBS.DTOBS,
    OBS.CODUSU,
    OBS.OBS,
    OBS.PENDENTELOG,
    OBS.DTHSOBS,
    OBS.REGINC,
    OBS.DHPROXCONTATO,
    OBS.ID,
    OBS.FIMATT

FROM AD_PRONTUARIOOBS OBS

LEFT JOIN AD_PRONTUARIOATT ATT (NOLOCK) ON ATT.PEDIDOEXTERNO = OBS.PEDIDOEXTERNO

Today I am developing the above query, column B would refer to table AD_PRONTUARIOATT

  • For me to answer with an example in your table, tell me which field of the table AD_PRONTUARIOOBS, that if it is NULL, has to bring what field of AD_PRONTUARIOATT?

  • @Rbz field OBS.FIMATT.

  • OBS.FIMATT of AD_PRONTUARIOOBS... But what about the AD_PRONTUARIOATT?

  • @Rbz the field only exists in the table AD_PRONTUARIOOBS even, I ended up missing the question, the field is only of this table.

  • If OBS.FIMATT for NULL, then you have nothing to bring from the other referenced table? kkk

  • So when this field is filled it should be displayed on the screen, when null should not be displayed, I just put the field there to show you what it was, in the other table I will only bring the external request that I have not yet entered...

Show 1 more comment

1 answer

5


Using the CASE:

SELECT 
(CASE WHEN A.campo1 IS NULL THEN B.campo1 ELSE A.campo1 END) as Resultado
FROM tabelaA A
LEFT JOIN tabelaB B ON B.id = A.idB

You can also use IIF, as said by @Robertodecampos

SELECT 
IIF(A.campo1 IS NULL, B.campo1, A.campo1) as Resultado
FROM tabelaA A
LEFT JOIN tabelaB B ON B.id = A.idB
  • 3

    Can be simplified as well: IF(A.campo1 IS NULL, B.campo1, A.campo1), I think it looks better for reading.

  • @Robertodecampos Boa Roberto! Edited!

  • @Robertodecampos taking advantage, the IF usually works on all Dbms? I didn’t notice this...

  • 1

    I don’t know if it works at all, at SQL-Server and in the MySQL works.

  • 2

    Attention, is not the IF which works on SQL Server queries, but the IIF. And not in every version.

  • @Joãomartins Boa João! Corrected! ^

Show 1 more comment

Browser other questions tagged

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