2009-07-09 32 views
0

正確嵌套時遇到問題我正在嘗試生成配方數據庫的xml文件,該配方數據庫的配方中含有成分作爲子元素。我的查詢是這樣的:使用SQL Server FOR XML EXPLICIT

select 
    1 as 'Tag' 
,null as 'parent' 
,replace(r.recipe_name, '/', '') as 'item!1!title!element' 
,isnull(replace(r.description, '/', ''), '') as 'item!1!description!cdata' 
,r.recipe_id as 'item!1!recipe_id!element' 
,null as 'ingredients!2!ingredient!element' 
from recipe r 
union all 
select 
    2 as 'Tag' 
    ,1 as 'parent' 
    ,null as 'item!1!title!element' 
    ,null as 'item!1!description!cdata' 
    ,r.recipe_id as 'item!1!recipe_id!element' 
    ,i.full_ingredient_txt as 'ingredients!2!ingredient!element' 
from 
    recipe r, ingredient i 
    where r.recipe_id = i.recipe_id 
order by 'item!1!recipe_id!element' 
for xml explicit 

產生以下XML:

<item> 
    <title>3-D Cookie Packages</title> 
    <description><![CDATA[]]></description> 
    <recipe_id>52576</recipe_id> 
    <ingredients> 
    <ingredient>Assorted candy decorations, if desired</ingredient> 
    </ingredients> 
    <ingredients> 
    <ingredient>cup butter or margarine, softened</ingredient> 
    </ingredients> 
    <ingredients> 
    <ingredient>cup sugar</ingredient> 
    </ingredients> 
</item> 

我真正想要的是我的成分,巢這樣的:

<ingredients> 
     <ingredient>Assorted candy decorations, if desired</ingredient> 
     <ingredient>cup butter or margarine, softened</ingredient> 
     <ingredient>cup sugar</ingredient> 
    </ingredients> 

我不能使用XML PATH,因爲我需要在描述字段中使用此方法不支持的CDATA聲明。

回答

1

這應該這樣做。添加額外的水平,以舉行父母成分節點

select 
1 as Tag 
,null as Parent 
,replace(r.recipe_name, '/', '') as 'item!1!title!element' 
,isnull(replace(r.description, '/', ''), '') as 'item!1!description!cdata' 
,r.recipe_id as 'item!1!recipe_id!element' 
,null as 'ingredients!2!' 
,null as 'ingredient!3!' 
from recipe r 
union all 
    select 
    2 as Tag 
    ,1 as Parent 
    ,null 
    ,null 
    ,r.recipe_id 
    ,'' 
    ,null 
from recipe r 
union all 
    select 
    3 as Tag 
    ,2 as Parent 
    ,null 
    ,null 
    ,r.recipe_id 
    ,null 
    ,i.full_ingredient_txt 
from 
    recipe r, ingredient i 
    where r.recipe_id = i.recipe_id 
order by 'item!1!recipe_id!element' 
for xml explicit 
+0

工程就像一個魅力。謝謝。只有我必須做出的改變是在第一個union聲明之後添加一個select語句。 – 2009-07-09 20:05:01