2016-11-28 98 views
3

我有一組動態查詢,它們以varchars的形式返回XML,見下文。SQL Server 2008:在動態XML查詢中返回空值

例子查詢:

set @sqlstr = 'Select ''<?xml version="1.0" encoding="windows-1252" ?>'' + ''<File_Name><Location>'' + (Select a,b,c from table for xml path(''Row'')) + </Location></File_name>''' 

exec(@sqlstr) 

此作品一種享受,直到select a,b,c ...查詢爲空。然後,我沒有收到外部因素如你所期望的一樣:

<?xml version="1.0" encoding="windows-1252"><File_Name><Location><Row></Row></Location></File_name> 

所有我收到是NULL

後有點谷歌搜索,我發現這個問題是NULL結果的拼接是一個完整的NULL結果。然而,我找不到一個解決方案給我我期望的結果。

我試過(不要說我已經試過正確)

IsNull(Exec(@sqlstring),'*blank elements*') 
xsnil (doesn't seem to work in dynamic queries) 
@result = exec(@sqlstring) then isnull and select 

任何人都有一個更好的解決辦法? (最好是小,由於多個這樣的查詢)

回答

1

我想你需要的東西是這樣的:

set @sqlstr = 'Select ''<?xml version="1.0" encoding="windows-1252" ?><File_Name><Location>'' + (Select IsNull(a, '') as a, IsNull(b, '') as b,IsNull(c, '') as c from table for xml path(''Row'')) + </Location></File_name>''' 

exec(@sqlstr) 
+1

這是我的錯誤,我做了A,B,C爲例如其實際*作爲其在某些情況下20領域。你的答案將起作用,如果沒有更短的方法,那麼必須列出每一個,然後我會接受作爲答案,謝謝 –

+0

如果有一個更短的方式,讓我知道,所以我可以學習@LRiley –

+0

我會做'將張貼任何答案,我找到 –