跟小D每日学口语

Create XML Files Out Of SQL Server With SSIS And FOR XML Syntax

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 varchar(38))
  3. go
  4.  
  5. create table Album(AlbumID int primary key not null,
  6. ArtistID int not null,
  7. AlbumName varchar(100) not null,
  8. YearReleased smallint not null)
  9. go
  10.  
  11.  
  12. insert into Artist values(1,'Pink Floyd')
  13. insert into Artist values(2,'Incubus')
  14. insert into Artist values(3,'Prince')
  15.  
  16. insert into Album values(1,1,'Wish You Were Here',1975)
  17. insert into Album values(2,1,'The Wall',1979)
  18.  
  19.  
  20.  
  21. insert into Album values(3,3,'Purple Rain',1984)
  22. insert into Album values(4,3,'Lotusflow3r',2009)
  23. insert into Album values(5,3,'1999',1982)
  24.  
  25.  
  26. insert into Album values(6,2,'Morning View',2001)
  27. insert into Album values(7,2,'Light Grenades',2006)

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.  
  8. select @XmlOutput
  9. 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

Execute SQL Task

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

Execute SQL Task Adding A Resultset

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

SSIS Script Task

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.  
  5. Imports System
  6. Imports System.Data
  7. Imports System.Math
  8. Imports Microsoft.SqlServer.Dts.Runtime
  9.  
  10.  
  11. Public Class ScriptMain
  12.  
  13.    
  14.  
  15.     Public Sub Main()
  16.         '
  17.         ' Add your code here
  18.         '
  19.         Dim XMLString As String = " "
  20.  
  21.  
  22.  
  23.         XMLString = Dts.Variables("XMLOutput").Value.ToString.Replace("<ROOT>", "").Replace("</ROOT>", "")
  24.         XMLString = "<?xml version=""1.0"" ?>" + XMLString
  25.  
  26.         GenerateXmlFile("C:\\MusicCollection.xml", XMLString)
  27.  
  28.     End Sub
  29.  
  30.     Public Sub GenerateXmlFile(ByVal filePath As String, ByVal fileContents As String)
  31.  
  32.         Dim objStreamWriter As IO.StreamWriter
  33.         Try
  34.  
  35.             objStreamWriter = New IO.StreamWriter(filePath)
  36.  
  37.             objStreamWriter.Write(fileContents)
  38.  
  39.             objStreamWriter.Close()
  40.  
  41.         Catch Excep As Exception
  42.  
  43.             MsgBox(Excep.Message)
  44.  
  45.         End Try
  46.         Dts.TaskResult = Dts.Results.Success
  47.     End Sub
  48.  
  49. 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.  
  5. Imports System
  6. Imports System.Data
  7. Imports System.Math
  8. Imports Microsoft.SqlServer.Dts.Runtime
  9.  
  10. <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
  11. <System.CLSCompliantAttribute(False)> _
  12. Partial Public Class ScriptMain
  13.     Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
  14.  
  15.     Enum ScriptResults
  16.         Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
  17.         Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
  18.     End Enum
  19.    
  20.  
  21.    
  22.  
  23.     Public Sub Main()
  24.         '
  25.         ' Add your code here
  26.         '
  27.         Dim XMLString As String = " "
  28.  
  29.  
  30.  
  31.         XMLString = Dts.Variables("XMLOutput").Value.ToString.Replace("<ROOT>", "").Replace("</ROOT>", "")
  32.         XMLString = "<?xml version=""1.0"" ?>" + XMLString
  33.  
  34.         GenerateXmlFile("C:\\MusicCollection.xml", XMLString)
  35.  
  36.     End Sub
  37.  
  38.     Public Sub GenerateXmlFile(ByVal filePath As String, ByVal fileContents As String)
  39.  
  40.         Dim objStreamWriter As IO.StreamWriter
  41.         Try
  42.  
  43.             objStreamWriter = New IO.StreamWriter(filePath)
  44.  
  45.             objStreamWriter.Write(fileContents)
  46.  
  47.             objStreamWriter.Close()
  48.  
  49.         Catch Excep As Exception
  50.  
  51.             MsgBox(Excep.Message)
  52.  
  53.         End Try
  54.  
  55.         Dts.TaskResult = ScriptResults.Success
  56.  
  57.  
  58.     End Sub
  59.  
  60. 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.

posted @ 2013-08-01 22:58  Danny Chen  阅读(382)  评论(0编辑  收藏  举报