简体   繁体   English

在T-SQL中用于XML导出的数据透视数据

[英]Pivot Data for XML Export in T-SQL

I have a table in my database that looks like this: 我的数据库中有一个表,如下所示:

@attribute       element       data
--------------------------------------
attribute1       element1      data1
attribute2       element2      data2

I want to output XML that looks like this: 我想输出看起来像这样的XML:

<element1 attribute="attribute1">data1</element1>
<element2 attribute="attribute2">data2</element2>

There are about 30 attribute element names, sorry, and they're somewhat dynamic. 抱歉,大约有30个 属性 元素名称,它们有些动态。 I'm not all that practiced or knowledgeable in SQL. 我不是所有在SQL中实践或知识丰富的人。 Is there a straightforward solution? 有一个简单的解决方案吗? Barring that, is there a "best-practice" solution? 除此以外,是否有“最佳实践”解决方案? If I use dynamic SQL, what measures should I take to catch/prevent potential errors? 如果使用动态SQL,应该采取什么措施来捕获/预防潜在的错误?

doesn't really form a valid xml since you're not specifying a root in your sample output but you can do something like this. 不会真正形成有效的xml,因为您没有在示例输出中指定根,但是您可以执行以下操作。

SELECT  CAST('<' + element + ' attribute="' + attribute + '">' + data + '</' + element + '>' AS XML)
FROM    Table1
FOR     XML PATH('')

By adding FOR XML RAW at the end of any query will produce XML close to what you are looking for. 通过在任何查询的末尾添加FOR XML RAW ,将生成与您要查找的XML接近的XML。 Also, you can specify element name by adding it at the end, such as FOR XML RAW ('ELEMENT_PARENT') , or a root name, FOR XML RAW ('ELEMENT_PARENT'), ROOT ('Example') . 此外,您可以通过在元素末尾添加元素名称来指定它,例如FOR XML RAW ('ELEMENT_PARENT')或根名称FOR XML RAW ('ELEMENT_PARENT'), ROOT ('Example')

As for as dynamic elements (or attributes before they are XML-ized) and error catching, you can employ any of standard bag of tricks offered by sql. 至于动态元素(或XML之前的属性)和错误捕获,您可以使用sql提供的任何标准技巧。

FWIW, I found this site that walks through several different examples with increasing complexity on ways to output XML data from a SQL script. FWIW,我发现此站点遍历了几个不同的示例,这些示例在从SQL脚本输出XML数据的方式上越来越复杂。

https://www.simple-talk.com/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/ https://www.simple-talk.com/sql/learn-sql-server/using-the-for-xml-clause-to-return-query-results-as-xml/

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

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