备份表为xml或csv文件,内容为长文本

时间:2012-10-03 02:26:20

标签: sql-server xml

我有一个表格,其中包含我要导出到xml文件的内容(如博客帖子,文字相当长)。

所以我想要它:

<table>
  <column1>1231</column1>
  <column2>January 1, 2001</column2>
  <column3>some very long text will all types of characters in it</column3>
</table>

是否有内置方法可以做到这一点?

基本上每列都有自己的元素。

理想情况下,内容应该是CDATA,因为内容可能包含任何类型的字符。

我有sql server 2008 express。

2 个答案:

答案 0 :(得分:1)

您可以使用FOR XML SQL构造来执行此操作。请阅读here

答案 1 :(得分:1)

从SQL Server 2005开始,FOR XML子句提供了一种将SQL查询的结果转换为XML的方法。

E.g。 考虑使用Blgd,Suit,SQFT,PDate列构建表。

SELECT * FROM building FOR XML AUTO

会将table的内容转换为以下XML:

<building Bldg="1" SUit="1" SQFT="1000" PDate="2012-09-24T00:00:00" />
<building Bldg="1" SUit="1" SQFT="1500" PDate="2011-12-31T00:00:00" />

如果您希望列成为元素,那么

SELECT * FROM building FOR XML AUTO, ELEMENTS

会将内容转换为以下XML:

<building>
  <Bldg>1</Bldg>
  <SUit>1</SUit>
  <SQFT>1000</SQFT>
  <PDate>2012-09-24T00:00:00</PDate>
</building>
<building>
  <Bldg>1</Bldg>
  <SUit>1</SUit>
  <SQFT>1500</SQFT>
  <PDate>2011-12-31T00:00:00</PDate>
</building>

如果要将文本字段建模为CDATA部分,则应使用FOR XML EXPLICIT子句并根据guidelines here定义XML架构。

如果上面的Building表有一个类型为TEXT的text_col列,应该在生成的XML中建模为CDATA部分,那么SELECT查询将如下所示:

SELECT 
    1 as Tag,
    NULL as Parent,
    Bldg AS [Building!1!Bldg!ELEMENT],
    text_col AS [Building!1!!CDATA]
FROM Building 
WHERE text_col IS NOT NULL
FOR XML EXPLICIT

结果如下:

<Building><Bldg>1</Bldg><![CDATA[From SQL Server 2005, the FOR XML clause provides a way to convert the results of an SQL query to XML.

E.g. Consider a table building with Blgd, Suit, SQFT, PDate columns.

SELECT * FROM building FOR XML AUTO

will convert the contents of table to the following XML:

<building Bldg="1" SUit="1" SQFT="1000" PDate="2012-09-24T00:00:00" />
<building Bldg="1" SUit="1" SQFT="1500" PDate="2011-12-31T00:00:00" />
If you want the columns to be elements, then

SELECT * FROM building FOR XML AUTO, ELEMENTS
would convert the contents to following XML:

<building>
  <Bldg>1</Bldg>
  <SUit>1</SUit>
  <SQFT>1000</SQFT>
  <PDate>2012-09-24T00:00:00</PDate>
</building>
<building>
  <Bldg>1</Bldg>
  <SUit>1</SUit>
  <SQFT>1500</SQFT>
  <PDate>2011-12-31T00:00:00</PDate>
</building>]]></Building>