LOOKUP Transformation task in SSIS 2008 to copy no match row from source to destination in SQL Server 2008

Yesterday I wrote one of the very simple articles to copy data from source SQL Server to destination at “Transfer data from one instance/database to another instance/database in SQL Server with SSIS”. You can use it, if task needs to be run only one time. If you want to keep running this job daily, weekly or after every certain period of time, you don’t need all data to be copied over again and again. You want to copy only those data which are not exists in destination table.
In order to achieve this task in SSIS 2008, we are going to use “LOOKUP Transformation” task between our source and destination. LOOKUP will do the job of checking source and destination. It can return match/not match data as per your need.
In order to do this job, we will need two dummy database and table in which we perform this exercise. Let us create two data ADV1 and ADV2, or you can use your two databases. Run following TSQL script.
–database 1
USE adv1
go
create table ChemicalConsume
(
      ChemID int,
      QuantityInLtr int,
      ConsumeDate datetime
)
GO
insert into ChemicalConsume
SELECT 1,10,’06/06/2010′ union all
SELECT 1,14,’06/07/2010′ union all
SELECT 2,8,’06/08/2010′ union all
SELECT 2,10,’06/09/2010′
GO
–database two
USE adv2
go
create table ChemicalConsume
(
      ChemID int,
      QuantityInLtr int,
      ConsumeDate datetime
)
GO
insert into ChemicalConsume
SELECT 1,10,’06/06/2010′
GO
Now, open BIDS and create new project for Integration Services and drop “Data Flow Task” in your work area from toolbox. To configure it, double click on that so that you will be redirected to the “Data Flow” tab.
Now, on dataflow tab, please drag “ADO NET Source” task from toolbox and drop it to your work area.
Double click on it to configure and set your database and table of ADV1 database there, for more information look at below screen shot.
Once your ADO NET Source is ready with configuration, drag “LOOKUP”  transformation task to your work area and join LOOKUP task with ADO NET SOURCE. Now, double click on “LOOKUP” to configure it.
Since, we want to copy only those rows which doesn’t exists in destination table, we have to select “Redirect rows to no match output” option from LOOKUP Transformation Editor and click on  “Connection” tab at left hand side.

From the connection tab, select your destination database and table. For more information, please look at the below given screen shot.

Now, please understand this concept, “ADO NET Source” returns row from ADV1.ChemicalConsume table which will be “Input” for our “LOOKUP” task. In the connection tab of LOOKUP task, we have made connection to “ADV2.ChemicalConsume” table as a destination so that LOOKUP will compare source and destination. 
Now from “LOOKUP Transformation Editor”  click on “Column” tab to set on which columns we are going to make comparison. Our comparison will be on “ChemID” and “ConsumeDate” fields of both the tables. So let us do it.
Now, take “ASP NET Destination” from tool box and join it with green arrow of “LOOKUP” task.
As soon as you will try to join green arrow of “LOOKUP” with “ASP NET Destination” you will get on small dialog box named “INPUT OUTPUT SELECTION”. Set the drop down value as shown in below screen
Now finally double click on “ADO NET Destination”  to configure it and set your ADV2 database along with appropriate table.
Now, run your package by hitting F5 and see output of the package.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

LOOKUP Transformation task in SSIS 2008 to copy no match row from source to destination in SQL Server 2008

Yesterday I wrote one of the very simple articles to copy data from source SQL Server to destination at “Transfer data from one instance/database to another instance/database in SQL Server with SSIS”. You can use it, if task needs to be run only one time. If you want to keep running this job daily, weekly or after every certain period of time, you don’t need all data to be copied over again and again. You want to copy only those data which are not exists in destination table.
In order to achieve this task in SSIS 2008, we are going to use “LOOKUP Transformation” task between our source and destination. LOOKUP will do the job of checking source and destination. It can return match/not match data as per your need.
In order to do this job, we will need two dummy database and table in which we perform this exercise. Let us create two data ADV1 and ADV2, or you can use your two databases. Run following TSQL script.
–database 1
USE adv1
go
create table ChemicalConsume
(
      ChemID int,
      QuantityInLtr int,
      ConsumeDate datetime
)
GO
insert into ChemicalConsume
SELECT 1,10,’06/06/2010′ union all
SELECT 1,14,’06/07/2010′ union all
SELECT 2,8,’06/08/2010′ union all
SELECT 2,10,’06/09/2010′
GO
–database two
USE adv2
go
create table ChemicalConsume
(
      ChemID int,
      QuantityInLtr int,
      ConsumeDate datetime
)
GO
insert into ChemicalConsume
SELECT 1,10,’06/06/2010′
GO
Now, open BIDS and create new project for Integration Services and drop “Data Flow Task” in your work area from toolbox. To configure it, double click on that so that you will be redirected to the “Data Flow” tab.
Now, on dataflow tab, please drag “ADO NET Source” task from toolbox and drop it to your work area.
Double click on it to configure and set your database and table of ADV1 database there, for more information look at below screen shot.
Once your ADO NET Source is ready with configuration, drag “LOOKUP”  transformation task to your work area and join LOOKUP task with ADO NET SOURCE. Now, double click on “LOOKUP” to configure it.
Since, we want to copy only those rows which doesn’t exists in destination table, we have to select “Redirect rows to no match output” option from LOOKUP Transformation Editor and click on  “Connection” tab at left hand side.

From the connection tab, select your destination database and table. For more information, please look at the below given screen shot.

Now, please understand this concept, “ADO NET Source” returns row from ADV1.ChemicalConsume table which will be “Input” for our “LOOKUP” task. In the connection tab of LOOKUP task, we have made connection to “ADV2.ChemicalConsume” table as a destination so that LOOKUP will compare source and destination. 
Now from “LOOKUP Transformation Editor”  click on “Column” tab to set on which columns we are going to make comparison. Our comparison will be on “ChemID” and “ConsumeDate” fields of both the tables. So let us do it.
Now, take “ASP NET Destination” from tool box and join it with green arrow of “LOOKUP” task.
As soon as you will try to join green arrow of “LOOKUP” with “ASP NET Destination” you will get on small dialog box named “INPUT OUTPUT SELECTION”. Set the drop down value as shown in below screen
Now finally double click on “ADO NET Destination”  to configure it and set your ADV2 database along with appropriate table.
Now, run your package by hitting F5 and see output of the package.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Transfer data from one instance/database to another instance/database in SQL Server with SSIS

There are many occasions where you need to transfer data from one instance/database of SQL Server to another instance/database of SQL Server. May be archiving, may be for ware house etc.
This is really very much needed utility, not only that, I have came across this question many times in different forums so though to explain this in my blog.
Today, I am not going into much details of each aspect, just transfer data from one source of SQL Server to another source.
Well, open new project from your VS2008. Project type “Business Intelligence Projects” and template should be “Integration services project”.
As soon as you create new project, drag “DataFlow” from tool box to “control flow” which is your work area. See image below for more detail

To configure that “dataflow” double click on that so that you will be redirected to the “Data Flow” tab, right beside “Control Flow” tab.
Now, take Ado.Net Source and Ado.Net Destination task from tool box and drop it into your work area. Connect Ado.Net Destination with Ado.Net Source. Now we will configure both tasks one by one.
Double click on Ado.Net Source task to configure it.
Note: I assume our source is AdventrueWorks database and HumanResouce.Employee table and destination is DataBaseNew on same server. Destination table should be created as “HREmployee” in destination database.
Create your database connection by clicking on “New” button in “Ado.net connection manager”.
From “Data Access Mode” select “Table or View” and from “Name of the table or View” should be “HumanResouce.Employee”. Configuration should look like this:

 Now, double click on “Ado.Net Destination” task. Set the destination database. If you already have table in destination database than select it or click on “new” and create one. Finally click on OK button and run the package by hitting “F5” and confirm whether data is there in your destination database.
This is really very basic example, I will post few more advanced article for this in very near future.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

For Loop container example in SSIS with C# script

Looping is one of the powerful tools since very long in each programming language. It has no different concept in SSIS too. Here in SSIS, For Loop container defining repetitive control flow in a package.
Generally in looping, three steps are very important. 1.) Initialization of loop variable 2.) condition for exiting the loop 3.) Increment/Decrement. In SSIS too, you have to be familiar with three steps only in order to execute For Loop Container.
 Let us now see the small example.
Create new project in BIDS (Business Intelligence Developer Studio) for this example and add two variables in the variable window.
1.)    “Count” type of Int32 with value of 5
2.)    “Increment” type of Int32 with value of 0
Once you are done with adding variable, drag For Loop container from tool box and drop it to the work area.  To configure loop container, double click on that.
Now, set following properties in “For Loop Editor”
1.)    InitExpression to @Increment=1
2.)    EvalExpression to @Icrement<@Count
3.)    AssignExpression to @Increment=@Increment+1
See the second paragraph of this article where I have mentioned three important steps for looping in programming language, same kind of three steps with different name we are setting up in “For Loop” container here in SSIS.
For more details, look at below screen shot.

Actually we are going to show message box for each iteration of “For Loop” container. Our Increment variable is set to 1 and it will run until it becomes greater than count variable which is 5. Show for displaying the message we are going to use “Script Task”.
Once you setup “For Loop” container, drag “Script Task” from tool box and put it inside “For Loop” container, double click on “Script Task” to configure it. We are going to use “Increment” variable inside the script task to display which iteration is going on. For using Increment variable, we have to select that variable in Script task. So, in “ReadWriteVariables” property of script task should have “Increment” variable, you can select that variable by clicking on Ellipse button besides “ReadWriteVariables” property. Once you set it, click on “Edit Script” button to write down script.
For more details, look at image below:

Once, you will click on “Edit Script” button, you will find one script edition and find “Main” method, which is our entry point, in that script editor. Put below given code in Main method and close “Script Editor” and click “OK” button in “Script Editor” dialog box.
System.Windows.Forms.MessageBox.Show(“Hi from SSIS, right now loop counter is at “ +  Dts.Variables[“Increment”].Value.ToString(), “information”);
            Dts.TaskResult = (int)ScriptResults.Success;
Now, you are ready to run this simple application by hitting “F5”.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Dynamic name of text file generated by Script Task in SSIS 2008

Today, I came up with one of the most useful script used by ETL developer. I used to see many questions about this issue so many times in different forums too.
We are going to generate text file by calling one stored procedure.  I have already written an article which generate text file as an output of Stored Procedure.  But It was using Flat File Destination task to generate text file and it was having static file name.
Here in this article we are going to use power of variables in SSIS. We will use the query and dynamic file name stored in variables. As a pre-requisite, let us create one table and stored procedure.
CREATE TABLE StudDetail
(
StudentID INT,
PassYear VARCHAR(10),
Grades int,
Increase INT,
Decrease INT
)
GO
INSERT INTO StudDetail
SELECT 1, ’08-09′, 3333,0,0 union all
SELECT 1, ’09-10′, 4252,25,0 union all
SELECT 2, ’08-09′, 2100,0,0 union all
SELECT 2, ’09-10′, 2002,0,-10
GO
create proc usp_StudDetail 
as 
begin 
 select StudentID,PassYear,Grades from StudDetail 
end 
GO
After creating this table and SP, let us create one new project in BIDS for SSIS.
1.)    Add one variable in variable window named “ExecuteSP”, datatype “String”
2.)    Add another variable named “DynamicFileName”, datatype “String”. We want dynamic value for this variable so in property window, set “True” in “EvaluateAsExpression” property
3.)    Click on ellipse button in “Expression” property to set the expression which make dynamic file name. Set following string in “Expression” which will generate dynamic file name
“DynamicFileName_” + (DT_WSTR,2) Day(GETDATE()) +(DT_WSTR,2) Month(GETDATE()) +(DT_WSTR,4) Year(GETDATE()) +(DT_WSTR,4) DatePart(“mi”,GETDATE())+(DT_WSTR,4) DatePart(“second”,GETDATE())+”.txt”
To get clear idea about all these settings, look at the screen shot below.

 

Once you set up variables, now this is turn to set ado.net database connection.
In the connection manager at the bottom of the screen, right click and insert “New ado.net connection” and rename it to “AdoNetConn” from the property window. Look at the below screen shot.

Now, you are going to do real programming like you used to do in C# application, which is my favorite programming language. I am glad that Microsoft has given facility to write script in C# language in Microsoft Integration services 2008.
Anyway, add one script manager in your design area and double click on it to configure.  Select both variables which we have created in “ReadOnlyVariables” property and click on “Edit Script” button.  See below image for more information.

 

Now, write down following script in your MAIN method.
//storing dynamic file name in strFileName varialbe
            string strFileName = Dts.Variables[“DynamicFileName”].Value.ToString();
            //storing our TSQL in strSQL variable
            string strSQL = Dts.Variables[“ExecuteSP”].Value.ToString();
            //storing the directory in strDir where our dynamic text file will be generated.
            string strDir = “D:\\SSIS\\”;
            //getting connection string in strConn from the ado.net connection manager we have added in design time
            string strConn = this.Dts.Connections[“AdoNetConn”].ConnectionString.ToString();
           
            string strLine = “”;
            System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(strConn);
            sqlConn.Open();
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(strSQL, sqlConn);
            System.Data.SqlClient.SqlDataReader dr;
            dr = sqlCmd.ExecuteReader();
            //getting column header and writing it to file
            for (int i = 0; i < dr.FieldCount; i++)
            {
                strLine = strLine + dr.GetName(i).ToString() + “|”;
            }
            strLine = strLine.Substring(0, strLine.Length – 1);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(strDir + strFileName, true);
            sw.WriteLine(strLine);
            sw.Close();
            sw = null;
       
            //writing record set to file
            while (dr.Read())
            {
                strLine = “”;
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    strLine = strLine + dr.GetValue(i).ToString() + “|”;
                }
                strLine = strLine.Substring(0, strLine.Length – 1);
                System.IO.StreamWriter sw1 = new System.IO.StreamWriter(strDir + strFileName, true);
                sw1.WriteLine(strLine);
                sw1.Close();
                sw1 = null;
            }
            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
This is just a sample script to demonstrate; you can make it more generic, divide it into smaller function and call that in MAIN method.
Anyway, you are now ready to run package by hitting F5 after writing script, close script edition and close “Script task editor”.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Dynamic name of text file generated by Script Task in SSIS 2008

Today, I came up with one of the most useful script used by ETL developer. I used to see many questions about this issue so many times in different forums too.
We are going to generate text file by calling one stored procedure.  I have already written an article which generate text file as an output of Stored Procedure.  But It was using Flat File Destination task to generate text file and it was having static file name.
Here in this article we are going to use power of variables in SSIS. We will use the query and dynamic file name stored in variables. As a pre-requisite, let us create one table and stored procedure.
CREATE TABLE StudDetail
(
StudentID INT,
PassYear VARCHAR(10),
Grades int,
Increase INT,
Decrease INT
)
GO
INSERT INTO StudDetail
SELECT 1, ’08-09′, 3333,0,0 union all
SELECT 1, ’09-10′, 4252,25,0 union all
SELECT 2, ’08-09′, 2100,0,0 union all
SELECT 2, ’09-10′, 2002,0,-10
GO
create proc usp_StudDetail 
as 
begin 
 select StudentID,PassYear,Grades from StudDetail 
end 
GO
After creating this table and SP, let us create one new project in BIDS for SSIS.
1.)    Add one variable in variable window named “ExecuteSP”, datatype “String”
2.)    Add another variable named “DynamicFileName”, datatype “String”. We want dynamic value for this variable so in property window, set “True” in “EvaluateAsExpression” property
3.)    Click on ellipse button in “Expression” property to set the expression which make dynamic file name. Set following string in “Expression” which will generate dynamic file name
“DynamicFileName_” + (DT_WSTR,2) Day(GETDATE()) +(DT_WSTR,2) Month(GETDATE()) +(DT_WSTR,4) Year(GETDATE()) +(DT_WSTR,4) DatePart(“mi”,GETDATE())+(DT_WSTR,4) DatePart(“second”,GETDATE())+”.txt”
To get clear idea about all these settings, look at the screen shot below.

 

Once you set up variables, now this is turn to set ado.net database connection.
In the connection manager at the bottom of the screen, right click and insert “New ado.net connection” and rename it to “AdoNetConn” from the property window. Look at the below screen shot.

Now, you are going to do real programming like you used to do in C# application, which is my favorite programming language. I am glad that Microsoft has given facility to write script in C# language in Microsoft Integration services 2008.
Anyway, add one script manager in your design area and double click on it to configure.  Select both variables which we have created in “ReadOnlyVariables” property and click on “Edit Script” button.  See below image for more information.

 

Now, write down following script in your MAIN method.
//storing dynamic file name in strFileName varialbe
            string strFileName = Dts.Variables[“DynamicFileName”].Value.ToString();
            //storing our TSQL in strSQL variable
            string strSQL = Dts.Variables[“ExecuteSP”].Value.ToString();
            //storing the directory in strDir where our dynamic text file will be generated.
            string strDir = “D:\\SSIS\\”;
            //getting connection string in strConn from the ado.net connection manager we have added in design time
            string strConn = this.Dts.Connections[“AdoNetConn”].ConnectionString.ToString();
           
            string strLine = “”;
            System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(strConn);
            sqlConn.Open();
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(strSQL, sqlConn);
            System.Data.SqlClient.SqlDataReader dr;
            dr = sqlCmd.ExecuteReader();
            //getting column header and writing it to file
            for (int i = 0; i < dr.FieldCount; i++)
            {
                strLine = strLine + dr.GetName(i).ToString() + “|”;
            }
            strLine = strLine.Substring(0, strLine.Length – 1);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(strDir + strFileName, true);
            sw.WriteLine(strLine);
            sw.Close();
            sw = null;
       
            //writing record set to file
            while (dr.Read())
            {
                strLine = “”;
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    strLine = strLine + dr.GetValue(i).ToString() + “|”;
                }
                strLine = strLine.Substring(0, strLine.Length – 1);
                System.IO.StreamWriter sw1 = new System.IO.StreamWriter(strDir + strFileName, true);
                sw1.WriteLine(strLine);
                sw1.Close();
                sw1 = null;
            }
            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
This is just a sample script to demonstrate; you can make it more generic, divide it into smaller function and call that in MAIN method.
Anyway, you are now ready to run package by hitting F5 after writing script, close script edition and close “Script task editor”.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

HTTP Connection Manager and Script task to download file via HTTP in SSIS 2008 with C# syntax

Download file via HTTP connection task would have lots of coding in .NET but in SSIS this task become much much easier with the help of “HTTP Connection Manager” , “HTTP Connection Manager” is one of the connection member of rich set of stock connection in SQL Server 2008 integration services.
Let us move ahead with creating package which can download the file from HTTP. Open new SSIS project.
To add “HTTP Connection Manager” in your package, right click on “Connection Manager” window and click on “New Connection”, from the “New Connection” dialog box, select “HTTP” and click on “Add” button.
For more detail, please look at below screen shot:
Once you insert “HTTP Connection Manager”, double click on it to configure. It will open dialog box editor, you have to give the path of file you wanted to download in “Server Settings” property.

I wanted to download my blog header so I am giving path of the same which is as below.

for more detail, look at below screen shot.

Once you are done with setup of “HTTP Connection Manager”, drag “Script Task” from tool box and drop it to the “Control Flow” which is your design area. Double click on “Script Task” to configure it and click on “Edit Script” button to write down script.
In the MAIN()  method which is our Entry Point, I am going to have following script.
Microsoft.SqlServer.Dts.Runtime.HttpClientConnection httpConn;
            Object obj;
            try
            {
                obj = Dts.Connections[“HTTP Connection Manager”].AcquireConnection(null);
                httpConn = new HttpClientConnection(obj);
                httpConn.DownloadFile(“d:\\SQLHub.jpg”, true);
            }
            catch (Exception e)
            {
                Dts.Events.FireError(1, e.TargetSite.ToString(), e.Message, “”, 0);
            }
            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
As soon as you copy the script there, save and close script editor and run your package by hitting F5. You will see file created at the destination path. In this case, I would found SQLHub.JPG in D drive of my system.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com