简体   繁体   English

SQL Server 2014查询到特定的XML格式

[英]SQL Server 2014 query into specific XML format

I have been asked to provide some data in XML format to a 3rd party company. 我被要求向第三方公司提供XML格式的一些数据。 I am using SQL Server 2014 for this. 我正在使用SQL Server 2014。 I cannot find anything anywhere which relates to the format that has been requested. 我找不到任何与请求的格式相关的内容。

The format is as follows: 格式如下:

<Item>
    <p:attribute_name="Product">Coat</p:attribute>
    <p:attribute_name="Colour">Purple</p:attribute>
    <p:attribute_name="Material">Polyester, Nylon</p:attribute>
</Item>

The SQL code to get this is: 获得这个的SQL代码是:

SELECT
    Product,
    Colour,
    Material
FROM Products

Which returns this: 哪个返回:

ID    Product    Colour    Material
1     Coat       Purple    Polyester, Nylon

I would like to know if it is at all possible to return the results of the query into the XML format provided. 我想知道是否可以将查询结果返回到提供的XML格式。

Any help is appreciated 任何帮助表示赞赏

As stated in my comment, your target format is not valid and a namespace is missing. 正如我的评论中所述,您的目标格式无效且缺少命名空间。 My magic glass bulb tells me, that you are looking for something like this: 我的神奇玻璃灯泡告诉我,你正在寻找这样的东西:

EDIT: Sorry, my first code mixed the captions! 编辑:对不起,我的第一个代码混合了字幕!

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>
*/
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM