简体   繁体   English

如何从SQL以列名作为prop并将列值作为值MSSQL Server生成xml

[英]How to generate xml from SQL with Column Name as prop and Column Value as value MSSQL Server

I have a SQL Table which has the following columns 我有一个SQL表,其中包含以下列

  1. Name 名称
  2. FatherName 父亲姓名
  3. MotherName 母亲名字
  4. Nationality 国籍

I want to generate a XML by SQL Query Which will results as follows 我想通过SQL查询生成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>

How can I get this. 我怎么能得到这个。 Please help me 请帮我

Try it like this: 像这样尝试:

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')

The result 结果

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

The empty columns ( ,'' ) are needed to tell the engine to start a new element. 需要空列( ,''来告知引擎启动新元素。 Otherwise you'd get an error, because an attribute cannot live twice within the same element. 否则,您将得到一个错误,因为一个属性不能在同一个元素中存在两次。


Hi, 你好
You can use FOR XML RAW utility 您可以使用FOR XML RAW实用程序

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

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

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