2010-10-14 96 views
14

如何在SQL查詢的select子句中嵌入if語句? 我知道使用大小寫的情況下,然後X else y結束,但是如何以同樣的方式對記錄集中的每條記錄執行嵌套。tsql:是否有可能在select中嵌套case語句?

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 

這裏是我的嘗試:

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 

這是正確的?

回答

16

您可以用COALESCE簡化此。

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

是的。案件中的案件沒有任何問題。

雖然,這裏是你的腳本,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 

OR

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 

OR

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

我得到一個錯誤與'as'結局作爲誰..任何想法爲什麼? – phill 2010-10-14 20:32:18

+0

錯誤是關鍵字'as'附近的語法不正確。 – phill 2010-10-14 20:32:58

+0

我的答案有幾種不同的方式來編寫你的陳述是正確的。看到這些並添加您的評論 – 2010-10-14 20:35:02

0

嘗試了這一點:

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 

雖然你可以只使用​​3210喬建議。