如何在SELECT FOR XML
语句中生成节点名称?
说我有桌子:
declare @Products table (ID int, Name varchar(100))
insert into @Products (1, 'Balls')
insert into @Products (2, 'Paper')
insert into @Products (3, 'Beer')
我想要以下XML输出:
<Products>
<Balls @ID=1/>
<Paper @ID=2/>
<Beer @ID=3/>
</Products>
如果不可能,是否可以使用SQL Server XML DML做到这一点?
好吧,我不认为您可以FOR XML PATH
直接使用命令来做到这一点。
因此,经过三思而后行,我想出了以下解决方案,虽然有些尴尬,但却可以解决问题:
DECLARE @Products TABLE (ID int, Name varchar(100))
INSERT INTO @Products (id, name)
VALUES (1, 'Balls'),
(2, 'Paper'),
(3, 'Beer')
SELECT
CAST('<' + NAME + ' id="' + CAST(id AS VARCHAR) + '" />' AS XML)
FROM
@Products
FOR XML PATH(''), ROOT('Products')
输出:
<Products>
<Balls id="1" />
<Paper id="2" />
<Beer id="3" />
</Products>
这是SQL小提琴
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句