Abstract
This article explains how to extract SQL Statements found in Execute SQL Tasks of an SSIS package and save them into a delimited text file using C# programming language.
Requirements
Article
This article continues from another article which can be found here.
Launch Visual Studio 2008 and create an Integration Services Project. After the default (new) package has launched, drag a script task to the control flow pane.
Right-click to edit the script task. In your Script Task Editor ensure that you have selected Microsoft Visual C# as your programming language.
At the bottom of your Script Task Editor, click “Edit Script”.
Add the following namespaces:
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Dts.Tasks;
using Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.IO;
Proceed to load the package (that contains the Execute SQL Tasks you would like to extract and save).
Application app = new Application();
Load package
Package p = app.LoadPackage(“C:\\TEMP\\pkg_Execute_Sql_Tasks.dtsx”, null);
Declare variables that will be used to store extracted queries:
//string declare delimiter
string del = “|”; // You can also change it to tab (^) comma (,) etc
string src_query = “”;
string sql_task_name = “”;
Int32 i = 1;
Create a text file as follows:
FileStream fileStream = new FileStream(@”c:\\TEMP\\selectSIFISO_file.txt”, FileMode.OpenOrCreate);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
streamWriter.WriteLine(“src_query” + del + “sql_task_name”);
The rest of the code is as follows:
foreach (Executable executable in importPackage.Executables)
{
DtsContainer container = (DtsContainer)executable;
if (executable.GetType().Name == “TaskHost”)
{
i = i + 1;
TaskHost loop = (TaskHost)executable;
ExecuteSQLTask sqlTask = (ExecuteSQLTask)loop.InnerObject;
src_query = sqlTask.SqlStatementSource;
sql_task_name = container.Name;
string source = src_query;
string[] stringSeparators = new string[] { “GO” };
string[] result;
result = source.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in the result)
{
// Insert new records into the workbook
streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
streamWriter.WriteLine(s + del + sql_task_name, result);
}
}
}
streamWriter.Flush();
streamWriter.Close();
Dts.TaskResult = (int)ScriptResults.Success;
We then save the package in a file system.
SIFISO_app.SaveToXml(“C:\\TEMP\\pkg_Execute_Sql_Tasks.dtsx”, dyna_pkg, null);
Conclusion
It’s that simple!
You can now execute your script task and the package will be created in the location you specified.
0 Comments