Programmatically Execute SQL Server Package Task Using C#

This article explains how to execute an SSIS package task of a package that is stored in an SQL Server.

If the above requirements are all met, we will begin by launching the Microsoft Visual Studio edition.
Create a new project Integration Services Project which is located under Business Intelligence Projects.
After you have named the new project, proceed to click and drag the script task in the Control Flow pane of the new package.
Right-click the script task and click on “Edit”
Under the Script Task Editor change the “ScriptLanguage” to “Microsoft Visual C# 2008”.
In Project Explorer import relevant references and ensure that you have declared namespaces as below:
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;
After declarations, create an instance of the application and package:

Application SIFISO_app = new Application();
Package p = new Package();

Insert SQL Server connection:

ConnectionManager cm = p.Connections.Add(“OLEDB”);
cm.Name = “msdb_pkg”;
cm.ConnectionString = string.Format(
“Provider=SQLOLEDB.1;Data Source={0};Initial Catalog={1};Integrated Security=SSPI;”, “your_server_name”, “your_database_name”);

Insert an Execute Package Task onto a package and set component properties:

Executable exec = p.Executables.Add(“STOCK:ExecutePackageTask”);
TaskHost th = exec as TaskHost;
th.Properties[“Name”].SetValue(th, “Execute selectSIFISO Package”);
th.Properties[“Description”].SetValue(th, “Execute selectSIFISO Package”);
th.Properties[“Connection”].SetValue(th, “msdb_pkg”);
th.Properties[“ExecuteOutOfProcess”].SetValue(th, “False”);
th.Properties[“PackageName”].SetValue(th, “\\\\your_pkg_name”);

We then save the package into a file system.
Dts.TaskResult = (int)ScriptResults.Success;
SIFISO_app.SaveToXml(“C:\\\\TEMP\\\\pkg_Exec_Pkg_Tasks.dtsx”, dyna_pkg, null);
It’s that simple!
You can now execute your script task and the package will be created in the location you specified.

Leave a Comment