So you want to spit out some XML from SQL Server into a file, how can you do that? There are a couple of ways, I will show you how you can do it with SSIS. In the SSIS package you need an Execute SQL Task and a Script Task.

Let's get started

First create and populate these two tables in your database

  1. create table Artist (ArtistID int primary key not null,
  2. ArtistName ))
  3. go
  4. create table Album(AlbumID int primary key not null,
  5. ArtistID int not null,
  6. AlbumName ) not null,
  7. YearReleased smallint not null)
  8. go
  9. ,'Pink Floyd')
  10. ,'Incubus')
  11. ,'Prince')
  12. ,,)
  13. ,,)
  14. ,,)
  15. ,,)
  16. ,,)
  17. ,,)
  18. ,,)
 

Now create this proc

  1. create proc prMusicCollectionXML
  2. as
  3. declare @XmlOutput xml
  4. set @XmlOutput = (select ArtistName,AlbumName,YearReleased from Album
  5. join Artist on Album.ArtistID = Artist.ArtistID
  6. FOR XML AUTO, ROOT('MusicCollection'), ELEMENTS)
  7. select @XmlOutput
  8. go
 

After executing the proc

  1. exec prMusicCollectionXML
 

you will see the following output

  1. <MusicCollection>
  2. <Artist>
  3. <ArtistName>Pink Floyd</ArtistName>
  4. <Album>
  5. <AlbumName>Wish You Were Here</AlbumName>
  6. <YearReleased>1975</YearReleased>
  7. </Album>
  8. <Album>
  9. <AlbumName>The Wall</AlbumName>
  10. <YearReleased>1979</YearReleased>
  11. </Album>
  12. </Artist>
  13. <Artist>
  14. <ArtistName>Prince</ArtistName>
  15. <Album>
  16. <AlbumName>Purple Rain</AlbumName>
  17. <YearReleased>1984</YearReleased>
  18. </Album>
  19. <Album>
  20. <AlbumName>Lotusflow3r</AlbumName>
  21. <YearReleased>2009</YearReleased>
  22. </Album>
  23. <Album>
  24. <AlbumName>1999</AlbumName>
  25. <YearReleased>1982</YearReleased>
  26. </Album>
  27. </Artist>
  28. <Artist>
  29. <ArtistName>Incubus</ArtistName>
  30. <Album>
  31. <AlbumName>Morning View</AlbumName>
  32. <YearReleased>2001</YearReleased>
  33. </Album>
  34. <Album>
  35. <AlbumName>Light Grenades</AlbumName>
  36. <YearReleased>2006</YearReleased>
  37. </Album>
  38. </Artist>
  39. </MusicCollection>
 

So far so good, so how do we dump that data into a file? Create a new SSIS package add an ADO.NET Connection, name it AdventureWorksConnection Drop an Execute SQL Task onto your control flow and modify the properties so it looks like this

On the add a result set by clicking on the add button, change the variable name to User::XMLOutput if it is not already like that

Note!!! In SSIS 2008 this variable should be already created otherwise it will fail

Now execute the package. You will be greeted with the following message: Error: 0xC00291E3 at Execute SQL Task, Execute SQL Task: The result binding name must be set to zero for full result set and XML results. Task failed: Execute SQL Task In order to fix that, change the Result Name property from NewresultName to 0, now run it again and it should execute successfully.

Our next step will be to write this XML to a file. Add a Script Task to the package,double click the Script Task,click on script and type XMLOutput into the property of ReadWriteVariables. It should look like the image below

Click the Design Script button, this will open up a code window, replace all the code you see with this

  1. ' Microsoft SQL Server Integration Services Script Task
  2. ' Write scripts using Microsoft Visual Basic
  3. ' The ScriptMain class is the entry point of the Script Task.
  4. Imports System
  5. Imports System.Data
  6. Imports System.Math
  7. Imports Microsoft.SqlServer.Dts.Runtime
  8. Public Class ScriptMain
  9. Public Sub Main()
  10. '
  11. ' Add your code here
  12. '
  13. Dim XMLString As String = " "
  14. XMLString = Dts.Variables("XMLOutput").Value.ToString.Replace("<ROOT>", "").Replace("</ROOT>", "")
  15. XMLString = "<?xml version=""1.0"" ?>" + XMLString
  16. GenerateXmlFile("C:\\MusicCollection.xml", XMLString)
  17. End Sub
  18. Public Sub GenerateXmlFile(ByVal filePath As String, ByVal fileContents As String)
  19. Dim objStreamWriter As IO.StreamWriter
  20. Try
  21. objStreamWriter = New IO.StreamWriter(filePath)
  22. objStreamWriter.Write(fileContents)
  23. objStreamWriter.Close()
  24. Catch Excep As Exception
  25. MsgBox(Excep.Message)
  26. End Try
  27. Dts.TaskResult = Dts.Results.Success
  28. End Sub
  29. End Class
 

SSIS 2008 requires a code change Here is what the code should look like if you are running SSIS 2008

  1. ' Microsoft SQL Server Integration Services Script Task
  2. ' Write scripts using Microsoft Visual Basic 2008.
  3. ' The ScriptMain is the entry point class of the script.
  4. Imports System
  5. Imports System.Data
  6. Imports System.Math
  7. Imports Microsoft.SqlServer.Dts.Runtime
  8. <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
  9. <System.CLSCompliantAttribute(False)> _
  10. Partial Public Class ScriptMain
  11. Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
  12. Enum ScriptResults
  13. Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
  14. Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
  15. End Enum
  16. Public Sub Main()
  17. '
  18. ' Add your code here
  19. '
  20. Dim XMLString As String = " "
  21. XMLString = Dts.Variables("XMLOutput").Value.ToString.Replace("<ROOT>", "").Replace("</ROOT>", "")
  22. XMLString = "<?xml version=""1.0"" ?>" + XMLString
  23. GenerateXmlFile("C:\\MusicCollection.xml", XMLString)
  24. End Sub
  25. Public Sub GenerateXmlFile(ByVal filePath As String, ByVal fileContents As String)
  26. Dim objStreamWriter As IO.StreamWriter
  27. Try
  28. objStreamWriter = New IO.StreamWriter(filePath)
  29. objStreamWriter.Write(fileContents)
  30. objStreamWriter.Close()
  31. Catch Excep As Exception
  32. MsgBox(Excep.Message)
  33. End Try
  34. Dts.TaskResult = ScriptResults.Success
  35. End Sub
  36. End Class
 

There are a couple of things you need to know, the XML will be generated inside a <ROOT> tag, I am stripping that out on line 23 of the code, on line 24 I am adding <?xml version="1.0" ?> to the file. Line 26 has the location where the file will be written, right now it is C:\MusicCollection.xml but you can modify that.

So now we are all done with this. It is time to run this package. Run the package and you should see that file has been created.

Create XML Files Out Of SQL Server With SSIS And FOR XML Syntax的更多相关文章

  1. SQL Server 2008中如何为XML字段建立索引

    from:http://blog.csdn.net/tjvictor/article/details/4370771 SQL Server中的XML索引分为两类:主XML 索引和辅助XML索引.其中辅 ...

  2. 在SQL Server中将数据导出为XML和Json

        有时候需要一次性将SQL Server中的数据导出给其他部门的也许进行关联或分析,这种需求对于SSIS来说当然是非常简单,但很多时候仅仅需要一次性导出这些数据而建立一个SSIS包就显得小题大做 ...

  3. 微软BI 之SSIS 系列 - 两种将 SQL Server 数据库数据输出成 XML 文件的方法

    开篇介绍 在 SSIS 中并没有直接提供从数据源到 XML 的转换输出,Destination 的输出对象有 Excel File, Flat File, Database 等,但是并没有直接提供 X ...

  4. Create maintenance backup plan in SQL Server 2008 R2 using the wizard

    You will need to identify how you want your maintenance plan to be setup. In this example the mainte ...

  5. SQL SERVER 原来还可以这样玩 FOR XML PATH

    FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前可能需要借助函数活存储过程来完成的工作.那么以一个实例为主 ...

  6. SQL Server 将数据导出为XML和Json

    有时候需要一次性将SQL Server中的数据导出给其他部门的也许进行关联或分析,这种需求对于SSIS来说当然是非常简单,但很多时候仅仅需要一次性导出这些数据而建立一个SSIS包就显得小题大做,而SQ ...

  7. Sql Server 部署SSIS包完成远程数据传输

    本篇介绍如何使用SSIS和作业完成自动更新目标数据任务. ** 温馨提示:如需转载本文,请注明内容出处.** 本文链接:https://www.cnblogs.com/grom/p/9018978.h ...

  8. SQL Server 2008 R2——使用FOR XML PATH实现多条信息按指定格式在一行显示

    =================================版权声明================================= 版权声明:原创文章 谢绝转载  请通过右侧公告中的“联系邮 ...

  9. SQL SERVER与SSIS 数据类型对应关系

随机推荐

  1. Asp.net vNext 学习之路(二)

    View component(视图组件)应该是MVC6 新加的一个东西,类似于分部视图.本文将演示在mvc 6中 怎么添加视图组件以及怎么在视图中注入一个服务. 本文包括以下内容: 1,创建一个新的a ...

  2. lr关联需要转义的常见字符

    转义字符总结     在做手动关联时,取边界值的时候,会经常用到转义字符,现将转义字符整理如下: \b 退格             \f 换页             \n 换行          ...

  3. lr回放Warning -26601报错的解决方法

    问题现象: Action2.c(30): Error -26601: Decompression function  (wgzMemDecompressBuffer) failed, return c ...

  4. SaltStack的配置管理--jinja (七)

    SaltStack的配置管理--jinja 需求场景:使用jinja模板,让各节点的httpd都监听在本机的ip [root@7mini-node1 apache]# vim files/httpd. ...

  5. OOD沉思录 --- 面向动作与面向对象 --- 避免泛滥成灾的类

    3.7 从设计中取出不需要的类 只有Get/Set方法的类不算是一个必要的类,Get/Set方法也不算是有意义的行为.这种类降级为属性更加合适. 3.8 去除系统外部的类 如果一个类只调用系统领域的方 ...

  6. TopTicTacToe 开发文档

    团队成员: 1.张旭 2.余浩 3.孙闯 4.吴阳 5.王晓华 6.张国庆 开发文档地址:http://www.kancloud.cn/netcon/t4 代码项目地址:https://coding. ...

  7. Lock接口简介

    在Java多线程编程中,我们经常使用synchronized关键字来实现同步,控制多线程对变量的访问,来避免并发问题. 但是有的时候,synchronized关键字会显得过于沉重,不够灵活.synch ...

  8. Spring学习——什么是AOP

    在网上查找什么是AOP,查到了下面这段话,我感觉写得清晰明了,一下子就明白了什么是面向切面编程AOP. ———————————————————————————————————————————————— ...

  9. Android Service AIDL

    http://blog.csdn.net/liuhe688/article/details/6400385 在Android中,如果我们需要在不同进程间实现通信,就需要用到AIDL技术去完成. AID ...

  10. 【Java虚拟机】JVM学习笔记之GC

    JVM学习笔记二之GC GC即垃圾回收,在C++中垃圾回收由程序员自己来做,例如可以用free和delete来回收对象.而在Java中,JVM替程序员来执行垃圾回收的工作,下面看看GC的详细原理和执行 ...