我被要求向第三方公司提供XML格式的一些数据。我正在使用SQL Server 2014。我无法找到任何与所请求格式相关的内容。
格式如下:
<Item>
<p:attribute_name="Product">Coat</p:attribute>
<p:attribute_name="Colour">Purple</p:attribute>
<p:attribute_name="Material">Polyester, Nylon</p:attribute>
</Item>
获取此代码的SQL代码是:
SELECT
Product,
Colour,
Material
FROM Products
返回此内容:
ID Product Colour Material
1 Coat Purple Polyester, Nylon
我想知道是否可以将查询结果返回到所提供的XML格式。
感谢任何帮助
答案 0 :(得分:3)
如我的评论中所述,您的目标格式无效且缺少命名空间。我的神奇玻璃灯泡告诉我,你正在寻找这样的东西:
CREATE TABLE dbo.Test(ID INT,Product VARCHAR(100),Colour VARCHAR(100),Material VARCHAR(100));
INSERT INTO dbo.Test VALUES(1,'Coat','Purple','Polyester,Nylon');
WITH XMLNAMESPACES('test' AS p)
SELECT 'Product' AS [p:attributName/@name]
,Product AS [p:attributName]
,''
,'Colour' AS [p:attributName/@name]
,Colour AS [p:attributName]
,''
,'Material' AS [p:attributName/@name]
,Material AS [p:attributName]
FROM dbo.Test
FOR XML PATH('Item')
DROP TABLE dbo.Test;
/*
<Item xmlns:p="test">
<p:attributName name="Product">Coat</p:attributName>
<p:attributName name="Colour">Purple</p:attributName>
<p:attributName name="Material">Polyester,Nylon</p:attributName>
</Item>
*/
答案 1 :(得分:0)
DECLARE @t TABLE (
ID INT IDENTITY,
Product VARCHAR(50),
Colour VARCHAR(50),
Material VARCHAR(150)
)
INSERT INTO @t (Product, Colour, Material)
VALUES
('Coat', 'Purple', 'Polyester, Nylo'),
('test', 'test2', 'test3')
;WITH XMLNAMESPACES ('p' as p)
SELECT ID, val
FROM @t
CROSS APPLY (
SELECT val = (
SELECT
[@name] = t2.id,
[text()] = t2.[value]
FROM (
VALUES
('Product', Product),
('Colour', Colour),
('Material', Material)
) t2 (id, value)
FOR XML PATH('p:attribute'), ROOT('Item'), TYPE
)
) t2