2010-10-14 14 views
14

come faccio a incorporare un'istruzione nidificata if in una clausola select di una query sql? So usare il caso quando la condizione X e la fine poi, ma come si fa a fare un nidificato nello stesso modo per ogni record in un set di record.tsql: è possibile eseguire istruzioni caso nidificate in una selezione?

if x.boy is not null then 
    x.boy 
else if x.girl is not null 
    then x.girl 
else if x.dog is not null 
    then x.dog 
else 
    x.cat 

qui è il mio tentativo:

SELECT top 10 
     id, 
     case when x.boy <> NULL then 
      x.boy 
     else case when x.girl <> NULL 
      x.girl 
       else case when x.dog <> NULL 
      x.dog 
       else x.cat 

     end as Who 
from house x 

è corretto?

risposta

16

Si potrebbe semplificare questo con COALESCE.

SELECT TOP 10 id, COALESCE(x.boy, x.girl, x.dog, x.cat) as Who 
    FROM house x 
16

Sì. Non c'è niente di sbagliato in un caso all'interno di un caso.

Anche se, qui è lo script, scritto corectly:

SELECT top 10 
    id, 
    case 
     when x.boy IS NOT NULL then x.boy 
     else case 
      when x.girl IS NOT NULL THEN x.girl 
      else case 
       when x.dog IS NOT NULL THEN x.dog 
       else x.cat 
      end 
     end 
    end as Who 
from house x 

O

SELECT top 10 
    id, 
    case 
     when x.boy IS NOT NULL then x.boy 
     when x.girl IS NOT NULL THEN x.girl 
     when x.dog IS NOT NULL THEN x.dog 
     else x.cat 
    end as Who 
from house x 

O

SELECT top 10 
    id, 
    coalesce(x.boy, x.girl, x.dog, x.cat) AS Who 
from house x 
+0

ottengo un errore con il 'come' in fine come chi .. qualche idea perché? L'errore – phill

+0

è una sintassi errata accanto alla parola chiave "as". – phill

+0

La mia risposta ha alcuni modi diversi per scrivere la tua affermazione che sono corretti. Vedi quelli e aggiungi i tuoi commenti –

0

Prova questo fuori:

SELECT top 10 
     id, 
     case when x.boy Is Not NULL then x.boy 
     else 
       case when x.girl Is Not NULL then x.girl 
       else 
        case when x.dog Is Not Null Then x.dog 
        else x.cat End 
       End 

     end as Who 
from house x 

anche se si potrebbe utilizzare coalesce come Joe suggerito.

Problemi correlati