2014-04-02 64 views
1

我有一個存儲過程,它根據一些選擇創建一個XML字符串。SQL Server:顯示默認值爲NULL在選擇

有沒有一種方法可以顯示默認值,如果其中一個選擇返回NULL? 基本上我只想保持我的XML中的相同結構,而不管值是否爲NULL(當前XML僅顯示具有值的記錄)。

實例存儲過程:

SELECT  A.ranking, 
      (
       SELECT  B.groupName, 
          (
           SELECT  C.policy, 
              C.groupCount 
           FROM  @temp C 
           WHERE  C.ranking = A.ranking 
           AND   C.groupName = B.groupName 
           ORDER BY C.groupCount desc, C.policy 
           FOR XML PATH(''), ELEMENTS, TYPE 
          ) AS groupName 
       FROM  @temp B 
       WHERE  B.ranking = A.ranking 
       GROUP BY B.groupName 
       ORDER BY B.groupName 
       FOR XML PATH(''), ELEMENTS, TYPE 
      ) 
FROM  @temp A 
GROUP BY A.ranking 
ORDER BY A.ranking 
FOR XML PATH('policyRanking'), ELEMENTS, TYPE, ROOT('ranks') 

非常感謝任何幫助,蒂姆。

回答

1

嘗試這樣的事情

SELECT  coalesce(A.ranking,0) as ranking 
      (
       SELECT  coalesce(B.groupName,'') as groupName, 
          (
           SELECT  C.policy, 
              C.groupCount 
           FROM  @temp C 
           WHERE  C.ranking = A.ranking 
           AND   C.groupName = B.groupName 
           ORDER BY C.groupCount desc, C.policy 
           FOR XML PATH(''), ELEMENTS, TYPE 
          ) AS groupName 
       FROM  @temp B 
       WHERE  B.ranking = A.ranking 
       GROUP BY B.groupName 
       ORDER BY B.groupName 
       FOR XML PATH(''), ELEMENTS, TYPE 
      ) 
FROM  @temp A 
GROUP BY A.ranking 
ORDER BY A.ranking 
FOR XML PATH('policyRanking'), ELEMENTS, TYPE, ROOT('ranks') 
+0

謝謝!你能解釋一下這裏有什麼合併嗎? – user2571510

+1

COALESCE將輸入的值設置爲第二個參數,如果NULL – Madhivanan

+0

完美的列 - 非常感謝! – user2571510

3

使用ISNULL功能,通過更換每個空列(見表定義)與表達:

ISNULL (column , default_value)