[转]SSIS: By coding
本文转自:http://www.codeproject.com/Articles/604197/SSIS-By-coding
Introduction
SSIS
better known as “SQL Server Integration Services (SSIS)”, is a component of SQL Server. According to Wikipedia:-
“SSIS is a platform for data integration and workflow applications. It features a fast and flexible data warehousing tool used for data extraction, transformation, and loading (ETL). The tool may also be used to automate maintenance of SQL Server databases and updates to multidimensional cube data.”
In this write-up, I will demonstrate data transfer between two tables on same server using C#, creating package entirely through coding in step by step process. Though it very easy to create SSIS package through GUI (you just need to set few properties and your package is ready to execute), here I am demonstrating coding way to create SSIS package.
You Going to Learn (Index)
- Create two table in Database (Source and Destination)
- Setup Initial task for SSIS project
- Create SSIS Package
- Create Source And Destination Connection Manager object
- Create DATA Flow Task (Pipeline) – Heart of package
- Create Source Data source and assign Source Connection Manager
- Create Destination Data source and assign Destination Connection Manager
- Create Path between Source Output and Destination
- Input Map source output column to destination input column
- Save package and execute Actual Code
Step by Step
1. Create two table in Database (Source and Destination)
Create two dummy table by name SourceTable
and DestinationTable1
, with same fields like this:-

CREATE TABLE [dbo].[SourceTable](
[ID] [int] NOT NULL,
[Name] [varchar](20) NULL,
[Age] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[DestinationTable1](
[ID] [int] NOT NULL,
[Name] [varchar](20) NULL,
[Age] [int] NULL
) ON [PRIMARY]
Also I have filled some dummy data into the source table
ID | Name | Age |
1 | Alok | 30 |
2 | Ashish | 30 |
3 | Jasdeep | 30 |
4 | Ritesh | 35 |
2. Setup Initial task for SSIS project
- Create
C# window form based project
. Nothing fancy - Add button on the form and include
OnClick
event handler, we will do all the programming in the event handler - Now include supporting SSIS DotNet Assemblies into the project, for that right click on the References in Solution Explorer Browse to %Program Files%\Microsoft SQL Server\100\SDK\Assemblies Include following files
- Microsoft.SQLServer.DTSPipelineWrap
- Microsoft.SqlServer.DTSRuntimeWrap
- Microsoft.SqlServer.ManagedDTS
- Close add assemblies dialog and save the solution.
3. Create SSIS Package
Following code will create will create the package object

Package objPackage = new Package();
objPackage.Name = "SSISExample";
objPackage.PackageType = DTSPackageType.DTSDesigner100;
objPackage.VersionBuild = 1;
Above, we have created SSIS Package object and given its name “SSISExample” and defined package type as DTSPackageType.DTSDesigner100
, there are lot of other option too,Have a look here (here we meant to say we are creating Designer oriented package)
4. Create Source And Destination Connection Manager object
Before we move forward, its good to have over connection manager up and running, here I am creating two Oledb connections to same database, this connection will be used byOleDB Source and OleDB Destination.

var connectingString =
@"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestDB;Provider=SQLNCLI10.1;Persist Security Info=True;"; ConnectionManager oleDBConnSrc = objPackage.Connections.Add("OLEDB");
oleDBConnSrc.ConnectionString = connectingString;
oleDBConnSrc.Name = "SourceConnection"; ConnectionManager oleDBDestination = objPackage.Connections.Add("OLEDB");
oleDBDestination.ConnectionString = connectingString;
oleDBDestination.Name = "DestinationConnection";
Here I have provided connectingString contain the connection string of SQL Database I am connecting to. One thing you should take care, the user from which you are loggingTo Database should have write access right on it. oleDBConnSrc
and oleDBDestination
are two ConnectionManager object.
5. Create DATA Flow Task (Pipeline) – Heart of package
Now we come to most important part of the package, the actual battleground where all the import/export is done. Though it backend name is Pipeline, how on designer screen it known by name “Data Flow Task”, all the coding of our source and destination will done inside this Data Flow Task, and it’s pretty simple to create.

//Create DataFlowTask in the package
TaskHost dataFlowTaskHost = (TaskHost)objPackage.Executables.Add("SSIS.Pipeline.2");
dataFlowTaskHost.Name = @"SSISPipeline";
dataFlowTaskHost.FailPackageOnFailure = true;
dataFlowTaskHost.FailParentOnFailure = true;
dataFlowTaskHost.DelayValidation = false;
dataFlowTaskHost.Description = @"Data Flow Task"; //-----------Data Flow Inner component starts----------------
MainPipe dataFlowTask = dataFlowTaskHost.InnerObject as MainPipe;
From our package object we will add Pipeline object using objPackage.Executables.Add()
method and passing "SSIS.Pipeline.2"
as object name to create,' and provide default properties to task object. Now we get MainPipe
of created dataFlowTaskHost, and rest of the component is attached to this MainPipe
(dataFlowTask).
6. Create Source Data source and assign Source Connection Manager
Our pipeline has been successfully created in step 5, now using its mainpipe we will add the source oledb connection

// Create and configure an OLE DB source component.
IDTSComponentMetaData100 sourceOleDB = dataFlowTask.ComponentMetaDataCollection.New();
sourceOleDB.ComponentClassID = "DTSAdapter.OLEDBSource.2";
CManagedComponentWrapper srcDesignTime = sourceOleDB.Instantiate(); // The ProvideComponentProperties method creates a default output.
srcDesignTime.ProvideComponentProperties();
sourceOleDB.Name = "TestDB DATA Source";
Here, we create object in the dataFlowTask object, and assign ComponentClassID = "DTSAdapter.OLEDBSource.2",
to tell package that we are adding OLEDBSource adapter.After that we instantiate it design time component, and get’s it properties which we will assign subsequently

// Assign the connection manager.
sourceOleDB.RuntimeConnectionCollection[0].ConnectionManagerID = oleDBConnSrc.ID;
sourceOleDB.RuntimeConnectionCollection[0].ConnectionManager =
DtsConvert.GetExtendedInterface(oleDBConnSrc);
Now assign Source DB adapter with source connection manager, above code do that bit, now we will set property for table to open in read mode

// Set the custom properties of the source.
srcDesignTime.SetComponentProperty("AccessMode", 0); // Mode 0 : OpenRowset / Table - View
srcDesignTime.SetComponentProperty("OpenRowset", "[dbo].[SourceTable]"); // Connect to the data source, and then update the metadata for the source.
srcDesignTime.AcquireConnections(null);
srcDesignTime.ReinitializeMetaData();
srcDesignTime.ReleaseConnections();
Here AccessMode=0
denote we are opening database in view mode and OpenRowSet
property denote the table we want to open
7. Create Destination Data source and assign Destination Connection Manager
Code is similar to that’s of Source Adapter, except we will pass ComponentClassID
as "DTSAdapter.OleDbDestination", AccessMode
= 3 and OpenRowSet
Propertly contain the Destination Table

IDTSComponentMetaData100 destinationOleDb =
dataFlowTask.ComponentMetaDataCollection.New();
destinationOleDb.ComponentClassID = "DTSAdapter.OleDbDestination"; CManagedComponentWrapper destDesignTime = destinationOleDb.Instantiate();
destDesignTime.ProvideComponentProperties(); // Assign the connection manager.
destinationOleDb.RuntimeConnectionCollection[0].ConnectionManagerID = oleDBDestination.ID;
destinationOleDb.RuntimeConnectionCollection[0].ConnectionManager =
DtsConvert.GetExtendedInterface(oleDBDestination);
// Set the custom properties of the source. destDesignTime.SetComponentProperty("AccessMode", 3);
destDesignTime.SetComponentProperty("OpenRowset",
"[dbo].[DestinationTable1]");
// Connect to the data source, and then update the metadata for the source.
destDesignTime.AcquireConnections(null);
destDesignTime.ReinitializeMetaData();
destDesignTime.ReleaseConnections();
8. Create Path between Source Output and Destination Input
Now our source and destination adapter are ready. Also Source output column is ready, now we connection source output column with destination input column, so that destination become aware what comings its way. For that we will add path between them

// Create the path from source to destination
IDTSPath100 pathDestination = dataFlowTask.PathCollection.New();
pathDestination.AttachPathAndPropagateNotifications(sourceOleDB.OutputCollection[0],
destinationOleDb.InputCollection[0]);
Here AttachPathAndPropagateNotifications
method of initialize destination input from sourceoledb output, since we have only one output from the source db, we safely assume its array position at 0, similarly for destination
9. Map source output column to destination input column

// Get the destination's default input and virtual input.
IDTSInput100 destinationinput = destinationOleDb.InputCollection[0];
IDTSVirtualInput100 vdestinationinput = destinationinput.GetVirtualInput(); // Iterate through the virtual input column collection.
foreach (IDTSVirtualInputColumn100 vColumn in
vdestinationinput.VirtualInputColumnCollection)
{
IDTSInputColumn100 vCol = destDesignTime.SetUsageType(destinationinput.ID, vdestinationinput, vColumn.LineageID, DTSUsageType.UT_READWRITE); // check if the column exist in the destination table
string cinputColumnName = vColumn.Name;
var columnExist = (from item in destinationinput.ExternalMetadataColumnCollection.Cast<IDTSExternalMetadataColumn100>()
where item.Name == cinputColumnName
select item).Count();
// if yes map it
if (columnExist > 0)
destDesignTime.MapInputColumn(destinationinput.ID, vCol.ID,
destinationinput.ExternalMetadataColumnCollection[vColumn.Name].ID);
}
Here we get destination input column, mark them available in design view, then search for matching column name is destination table, if we found match, we map the column using MapInputColumn method
10. Save package and Execute Package
SSIS file is actually XML file, if you rename the dtsx file to xml, you can view all the property set by us, we will save it, and view it in the Business Intelligence studio

Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
app.SaveToXml(string.Format(@"c:\workSamplePackage\SamplePackage{0}.dtsx",
DateTime.Now.ToString("hhmmss")),
objPackage, null);
objPackage.Execute();
objPackage.Dispose();
app = null;
ScreenShot
If we open the above created package file in Business Intelligence studio, it would look like this :-
You could clearly see the two Connection manager, which we have added. Also source and Destination connection we have created., now if you run this, its show something like this :-
It say 4 rows has been transferred from source database to destination database, here have look at the destination table
[转]SSIS: By coding的更多相关文章
- 如何优化coding
如何优化coding 前言 最近一直在做修改bug工作,修改bug花费时间最多的不是如何解决问题而是怎样快速读懂代码.如果代码写的好的,不用debug就可以一眼看出来哪里出了问题.实际上,我都要deb ...
- SSIS 包部署 Package Store 后,在 IS 中可以执行,AGENT 执行却报错
可以执行 SSIS Package ,证明用 SSIS Package 的账户是可以执行成功的.SQL Server Agent 默认指定账号是 Network Service. 那么可以尝试一下将 ...
- 使用 Code Snippet 简化 Coding
在开发的项目的时候,你是否经常遇到需要重复编写一些类似的代码,比如是否经常会使用 for.foreach ? 在编写这两个循环语句的时候,你是一个字符一个字符敲还是使用 Visual Studio 提 ...
- SSIS 属性:ExecValueVariable
有些Task组件执行完成之后,会产生输出结果,称作Execution Value,例如,Execute SQL Task在执行完成之后,会返回受影响的数据行数.Task组件的Execution Val ...
- SSIS 实例——将SQL获取的信息传递到Email中
最近在为公司财务开发一个邮件通知时遇到了一个技术问题.原来我设计SSIS的是每天将ERP系统支付数据导出到财务支付平台后 Email 通知财务,然后财务到支付平台上进行支付操作.由于那个时候开发时间很 ...
- 介绍几种SSIS部署方式
介绍 如果你已经开发完一个不错的SSIS包并且能够在你的本地完美的运行,每个任务都亮起绿色的通过标志.这时为了能够让这个包处理能够在指定时间运行,你需要将其发布到一个服务器上,并做好相关配置.作为开发 ...
- 如何将本地项目与coding.net/github上的项目绑定
得到coding.net/github项目的ssh协议地址 形如:·git@git.coding.net:wzw/leave-a-message.git· 在本地生成公钥 输入 ssh-keyge ...
- 将本地项目提交到coding上托管
1: 注册coding并新建项目test2:在终端 cd 到要提交的项目 使用git init创建.git文件夹3:使用git pull <项目地址>https的那个4:git a ...
- Block Markov Coding & Decoding
Block Markov coding在一系列block上进行.在除了第一个和最后一个block上,都发送一个新消息.但是,每个block上发送的码字不仅取决于新的信息,也跟之前的一个或多个block ...
随机推荐
- hrbust - 2239
影子模仿术 Time Limit: 500 MS Memory Limit: 32768 K Total Submit: 7(5 users) Total Accepted: 2(2 users) R ...
- DataTable.DefaultView.Sort 排序方法
今天在整合一个东西,需要用到DataTable的一个排序方法, 前我是将DataTable存到DataView里面的,所以刚开始就使用了DataView.Sort="ColumnName A ...
- StyleCop setting
StyleCop下载地址:http://stylecop.codeplex.com/ -Documentation Rules 文档化注释规则 -Element Documentaion 变量的文档化 ...
- centos7系统安装后的基础优化
1.更改网卡信息 1.编辑网卡 # cd /etc/sysconfig/network-scripts/ # mv ifcfg-ens33 ifcfg-eth0 # mv ifcfg-ens37 if ...
- CentOS 6.4 系统上如何安装 tomcat 8
CentOS 6.4 系统上如何安装 tomcat 8 本文将详细讲解在Linux系统上如何安装tomcat,tomcat是没有32位和64位之分的. 1.下载tomcat 首先我们肯定要先下载tom ...
- 转:x64与x86的改变
http://tieba.baidu.com/p/1250470248 x64与x86的改变 硬件要求就是64位的CPU.操作系统也必须是64位的,如果在64位的CPU上安装了32位的操作系统,就算编 ...
- python的版本会导致IBus设置(中文输入法)出错
最近在学习python,可是,发现我的输入法 IBus-pinyin ,不能用了, 现象: 发现 “首选输入法”,根本点击不进去IBus设置的窗口,想去设置输入法都不行, IBus设置的窗口: 原因是 ...
- LCA算法笔记
LCA,最近公共祖先,实现有多种不同的方法,在树上的问题中有着广泛的应用,比如说树上的最短路之类. LCA的实现方法有很多,比如RMQ.树链剖分等. 今天来讲其中实现较为简单的三种算法: RMQ+时间 ...
- HRBUST 1212 乘积最大
$dp$,大数运算. $dp[i][j]$表示到$i$位置切成了$j$段的最大收益.数字爆$longlong$,$Java$上大数. import java.math.BigInteger; impo ...
- 浮生半日:探究Python字节码
好吧!“人生苦短,请用Python”,作为python爱好者以及安全从业者,而且最近也碰到了一些这方面的问题,懂点python字节码还是很有必要的. Python是一门解释性语言,它的具体工作流程如下 ...