如何从SQL生成xml,其中Column Name为prop,Column Value为value MSSQL Server

时间:2016-09-28 11:31:01

标签: sql sql-server xml

我有一个SQL表,其中包含以下列

  1. 命名
  2. FatherName
  3. MotherName
  4. 国籍
  5. 我想通过SQL Query生成XML,结果如下

    <Customer>
    <Prop ID="Name" ValStr="CustName" />
    <Prop ID="FatherName" ValStr="Mr.xxx" />
    <Prop ID="MotherName" ValStr="Mrs.yyy" />
    <Prop ID="Nationality" ValStr="ZZZ" />
    </Customer>
    

    我怎样才能得到这个。请帮帮我

2 个答案:

答案 0 :(得分:1)

试试这样:

DECLARE @tbl TABLE(Name VARCHAR(100),FatherName VARCHAR(100),MotherName VARCHAR(100),Nationality VARCHAR(100));
INSERT INTO @tbl VALUES
 ('Name1','FatherName1','MotherName1','Nationality1')
,('Name2','FatherName2','MotherName2','Nationality2');

SELECT 
    'Name' AS [Prop/@ID]
   ,Name AS [Prop/@ValStr]
   ,''
   ,'FatherName' AS [Prop/@ID]
   ,FatherName AS [Prop/@ValStr]
   ,''
   ,'MotherName' AS [Prop/@ID]
   ,MotherName AS [Prop/@ValStr]
   ,''
   ,'Nationality' AS [Prop/@ID]
   ,Nationality AS [Prop/@ValStr]
FROM @tbl
FOR XML PATH('Customer'),ROOT('root')

结果

<root>
  <Customer>
    <Prop ID="Name" ValStr="Name1" />
    <Prop ID="FatherName" ValStr="FatherName1" />
    <Prop ID="MotherName" ValStr="MotherName1" />
    <Prop ID="Nationality" ValStr="Nationality1" />
  </Customer>
  <Customer>
    <Prop ID="Name" ValStr="Name2" />
    <Prop ID="FatherName" ValStr="FatherName2" />
    <Prop ID="MotherName" ValStr="MotherName2" />
    <Prop ID="Nationality" ValStr="Nationality2" />
  </Customer>
</root>

需要空列(,''来告诉引擎启动新元素。否则你会收到一个错误,因为一个属性不能在同一个元素中存活两次。

答案 1 :(得分:0)

嗨,您可以使用 FOR XML RAW 实用程序

SELECT NAME, FATHERNAME, MOTHERNAME, NATIONALITY
FROM table_name 
FOR XML RAW ('ID');