如何使用SQL Server中的数据提供xml文件?

时间:2014-08-07 23:16:44

标签: sql sql-server xml

我需要定期提供特定格式的xml和我可以从SQL Server 2012获得的数据。这样做的正确或更有效的方法是尽可能地自动完成任务?我可以从SQL数据库中选择所有数据(标签的值),但是是否可以将它们保存为特定的XML格式并从查询中生成整个文件?或者我需要将数据注入该外部文件。一个客户端的xml文件如下所示:

<?xml version="1.0"?>
<AddCases>
<AddCase>
<Case>
<Debtor>
<Consumer>
<FirstName>John</FirstName>
<Surname>Doe</Surname>
<Citizenship>Mars</Citizenship>
<Birthday>1979-08-31</Birthday>
<SSN>79083102949</SSN>
<Address>
<Street>135 Main St</Street>
<City>Linden</City>
<ZipCode>5556</ZipCode>
<Country>US</Country>
</Address>
<Sex>men</Sex>
</Consumer>
</Debtor>

<History>
<InformationDate>2014-01-02</InformationDate>
<PaymentStatusCode>00</PaymentStatusCode>
<OverDue>0</OverDue>
<OverdueAmount>0</OverdueAmount>
<DueAmount>42000</DueAmount>
</History>
.
.
.
<SourceSymbol>pap</SourceSymbol>
</Consent>
</Consents>
</CreditAccount>
</CreditAccouts>
</Case>
</AddCase>

1 个答案:

答案 0 :(得分:1)

看看FOR XML。它提供了很多选项并返回XML以便您。我已经完成了很多显式模式查询,您可以使用联合查询每个图层。有点难看,但它有效。

select 1 as tag,
null as parent,
'' as [AddCases!1!xmlns],
null as [AddCase!2!xmlns],
null as [Case!3!xmlns],
null as [Debtor!4!FirstName!elementxsinil],
null as [Debtor!4!LastName!elementxsinil]

union 

select 2 as tag,
1 as parent,
null as [AddCases!1!xmlns],
'' as [AddCase!2!xmlns],
null as [Case!3!xmlns],
null as [Debtor!4!FirstName!elementxsinil],
null as [Debtor!4!LastName!elementxsinil]

union 

select 3 as tag,
2 as parent,
null as [AddCases!1!xmlns],
null as [AddCase!2!xmlns],
null as [Case!3!xmlns],
null as [Debtor!4!FirstName!elementxsinil],
null as [Debtor!4!LastName!elementxsinil]

union

select 4 as tag,
3 as parent,
null as [AddCases!1!xmlns],
null as [AddCase!2!xmlns],
null as [Case!3!xmlns],
'Jack' as [Debtor!4!First Name!elementxsinil],
'Smith' as [Debtor!4!Last Name!elementxsinil]
--your from here

for xml explicit

生成:

<AddCases xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="">
  <AddCase xmlns="">
    <Case>
      <Debtor>
        <FirstName>Jack</FirstName>
        <LastName>Smith</LastName>
      </Debtor>
    </Case>
  </AddCase>
</AddCases>

至于生成文件外观here。我可能会使用sqlcmd选项并使用Windows任务调度程序运行它以自动执行它。