如何转换MSSQL 2012表(#myTable),如下所示:
name|lastname|child1|age1|child2|age2|child3|age3| prnt|prnt2
Jack|Jones |Jill |2 |Joe |4 |Mike |5 | Mark| Lizy
到这样的XML格式:
<familyTree>
<firstname> Jack </firstname>
<lastname> Jones </lastname>
<babies>
<baby> Jill </baby>
<old> 2 </old>
<babies>
<babies>
<baby> Joe </baby>
<old> 4 </old>
<babies>
<babies>
<baby> Mike </baby>
<old> 5 </old>
<babies>
<father>Mark </father>
<mother>lizy </mother>
</familyTree>
这样的选择语句:
SELECT
name AS "firstname",
lastname AS "lastname",
child1 AS "babies/baby",
age1 AS "babies/old",
child2 AS "babies/baby",
age2 AS "babies/old",
child3 AS "babies/baby",
age3 AS "babies/old",
prnt AS "father",
prnt2 AS "mother"
FROM #myTable
FOR XML PATH('familyTree')
会导致:
<familyTree>
<firstname> Jack </firstname>
<lastname> Jones </lastname>
<babies>
<baby> Jill </baby>
<old> 2 </old>
<baby> Joe </baby>
<old> 4 </old>
<baby> Mike </baby>
<old> 5 </old>
<babies>
<father>Mark </father>
<mother>lizy </mother>
</familyTree>
该结构与上面给出的所需结构不同。任何帮助或正确方向的步骤将不胜感激?提前谢谢你。
答案 0 :(得分:1)
这是诀窍(如果将来有人试图克服同样的情况)。
SELECT
name AS "firstname",
lastname AS "lastname",
child1 AS "babies/baby",
age1 AS "babies/old",
'',
child2 AS "babies/baby",
age2 AS "babies/old",
'',
child3 AS "babies/baby",
age3 AS "babies/old",
prnt AS "father",
prnt2 AS "mother"
FROM #myTable
FOR XML PATH('familyTree')