添加一个以 NULL 作为值的列,为每列生成一个单独的项目节点。
SELECT
t.col1 as 'item'
,NULL
,t.col2 as 'item'
,NULL
,t.col3 as 'item'
FROM dbo.tbl as t
FOR XML PATH('parent'), TYPE;
Result:
<parent>
<item>1</item>
<item>2</item>
<item>3</item>
</parent>
SQL小提琴 http://sqlfiddle.com/#!6/2e29f/1
为什么这有效?
没有名称的列将作为文本节点插入。在这种情况下,NULL 值作为文本节点插入到item
nodes.
如果您添加实际值而不是 NULL,您将看到发生了什么。
SELECT
t.col1 as 'item'
,'1'
,t.col2 as 'item'
,'2'
,t.col3 as 'item'
FROM dbo.tbl as t
FOR XML PATH('parent'), TYPE;
Result:
<parent>
<item>1</item>1<item>2</item>2<item>3</item></parent>
指定没有名称的列的另一种方法是使用通配符*
作为列别名。
名称指定为通配符的列 https://msdn.microsoft.com/en-us/library/bb500154.aspx
在这种情况下,没有必要使用通配符,因为具有 NULL 值的列没有列名,但当您需要实际列中的值但不希望列名是节点名时,它很有用。