Friday, May 3, 2013

Loop through excel column names using SSIS

How do I get the field names from a specific excel sheet in an excel file? There was a question asked on SSIS MSDN forum which forced me to blog on this.

Suppose the excel file has more than one sheets and the sheet we are interested in is ImpData which has two columns (Data1 and Data2). The aim is to get these field names and check if these fields are present in a specific sql server table. If fields Data1 and Data2 are not present in the table then add them to the table. Once the columns are added to the table load the excel data to the sql server table.

Step1:Create a table ExcelFields (Field1 Varchar(20))

Step2:Create 4 package scoped string variables SheetName, FieldName, ExcelSheetName and AlterSQL. Set the value for SheetName as ImpData$ as this is the sheet that contains the relevant data to be fetched and loaded to sql server table.

Step3:Create an ado.net connection for the excel file. Use a foreach loop to iterate through excel sheets and save each of the sheet name in ExcelSheetName variable. Check my blog on how to create ado.net connection manager and save the excel sheet name in a variable.

Step4:Have a foreach loop within the foreach loop used to capture the sheet name (Step3) and click on Collection in the left pane in foreach loop editor. Select the enumerator as "Foreach ADO.NET Schema Rowset Enumerator". Under enumerator configuration select the ado.net connection created in Step2. Select "Columns" as Schema from the drop down box.
Click on "SetRestrictions" button and select Table_Catalog, Table_Schema and Table_Name. Highlight Table_Name and Select SheetName variable as shown:


 
Step5:Click on Variable Mappings in left pane and select the variable FieldName (created in Step1) and set the index as 3.

Following is the control flow so far:



















Step6: Put a dummy script task inside the outer foreach loop and hook it to the inner foreach loop container. Add a precedence constraint (Evaluation operation as expression and constraint and value as success)using following expression: @[User::SheetName]==@[User::ExcelSheetName].

Step7: Set the evaulate as expression property for variable AlterSQL as true and set the following expression: "Alter Table ExcelFields Add " +  @[User::FieldName] + "  Varchar (50)"

Step8: Add an execute sql task inside the inner foreach loop and set the connection manager to point to the table that needs to be altered. Use AlterSQL as the sql source in execute sql task.

Step9: An execute sql task can be added out of the both the foreach loops and be used to load the excel data to table using the distributed queries mentioned here.

Note: The expression for AlterSQL can be modified to check and ignore if the fields are already present in the table



Saturday, April 3, 2010

Error handling using script component

This post is just to show how to trigger an event handler for a data flow task if any component inside the same data flow task fails. This approach will work only for those data flow task components which have error output (Merge, Merge Join etc.. has no error op).
Poblem: Suppose I have a lookup component inside Data flow task and any mismatch should be treated as error and an appropriate error message should be sent using Send Mail Task.
Solution: Take a data flow task and configure it using an OLEDB source, lookup component and take the error op of lookup to a script component. Check
here for error handling using script component. The data flow task would be like:
Create a string variable (in this case the name of variable is Error) and use this variable as ReadWriteVariables inside script component editor as shown below:

Use following code inside the script transformation editor (I am using VB.Net code):
Now create an event handler for the data flow task for "On Task Failed" event and add a Send Mail Task. For demo purpose I am using a script task (as I don't have smtp server configured) as shown below:

Value of variable (Error) can be verified by adding following piece of code inside scipt task editor (don't forget to set Error variable as ReadOnlyVariable inside Scrpt task editor):
Public Sub Main()
System.Windows.Forms.MessageBox.Show(Dts.Variables("Error").Value.ToString())
Dts.TaskResult = ScriptResults.Success

End Sub

Saturday, January 16, 2010

Executing an SSIS package using batch file or stored procedure or xp_cmdshell

Creating a batch file and schedule it trough Task Scheduler or SQL Agent
Following is the script (same as used in executing the package through Dtexec command line utility except the value of the variable Mode) that is used in creating a batch file (crate a text file, paste the script and rename it to .bat):

A batch file can be schedules using a task scheduler or SQL Agent. Create a job and this time the step would be OS type job step. Give the actual path of batch file as shown below:

This batch file can be scheduled using windows task scheduler.

Using sp_start_job stored procedure to execute a sql agent job
Stored procedure sp_start_job can be used to execute the already created job. This stored procedure accepts various parameters, job name or job id being the mandatory parameter. Value of the variable “Mode” cannot be changed using this procedure. To verify the result in table, edit the job and set the value of variable Mode as Procedure. Then execute the procedure as:
EXEC msdb.dbo.sp_start_job N'SSISMode'
The procedure is available in msdb database so use this database while executing the procedure. The name of the job is SSISMode. To verify the result, check the table for an entry with value for column Execution Mode as Procedure

Using xp_cmdshell to execute a package from SSMS
Xp_cmdshell is off by default and needs to be enabled by a sysadmin. Check following links to enable xp_cmdshell in SQL Server 2005 and 2008:
SQL Server 2005 and
SQL Server 2008 Once the xp_cmdshell is enabled, write the command to execute the package. The command would be like: EXEC XP_CMDSHELL 'DTEXEC <Place Holder>' Use DtexecUI to set the value of variable Mode as Xp_cmdshell. Then click on Command Line tab and copy the command and paste it in the place holder above (). After executing the package check and verify the result in the table by selecting a column with Execution Mode as Xp_cmdshell. Using this method to execute a package is not recommended because the use of xp_cmdshell requires sysadmin privilege and thus it opens up a security hole. Note: When pasting the command in management studio, don’t try to split the lengthy command into multiple lines (using enter key) to avoid scrolling left and right. Check this link to know why not to do so



Previous

Executing an SSIS package through code or sql agent

Using code to execute the package
Create simple windows application to execute a package. Open Visual Studio and create a Windows Application. Add a reference to Micosoft.SQLServer.ManagedDTS as shown below:

In case SQL Server 2005 is used, then select version 9.0 and in case of SQL Server 2008 use the 10.0 version.
Add a button to the form and double click the button to add the following code in button click event:
String path = @" C:\ExecutionModesofSSIS\Package.dtsx";
Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
Package pack = app.LoadPackage(path, null);
pack.Variables["Mode"].Value = "CSharp";
DTSExecResult Result = pack.Execute();
MessageBox.Show(Result.ToString());
Add following using statement as well:
using Microsoft.SqlServer.Dts.Runtime
Build the solution and execute it. Check the result in the table. This time there will be an entry for Execution Mode as CSharp.

Using SQL Agent by creating a job (scheduled or unscheduled)
Create a job to execute the package from file system. Right click the SQL Agent by connecting to SQL Server Management Studio and select New Job. Give the job name as SSISMode and then click on Steps. Click on New to add a job step Execute as shown below:

SQL Agent Service Account is the default account which the SQL Agent will use while executing the package. Now click on Set Values tab shown in the above figure (Green colored box) and set the value of variable Mode as SQLAgent as shown below:

Once the value of variable Mode is set, finish the job by clicking OK. Don’t schedule the job (it can be scheduled by clicking on Schedule tab). Now right click the job and click on "Start Job at step…" as shown below:

Check and verify the result in table. There will be an entry for SQLAgent as Execution Mode inside the table. There is one column “Executing User Name” in the table which has not been considered yet. Check the value for that column. For all the execution modes other than SQLAgent, the executing user name will be same (the domain account like: ABCD\nitesh.rai) but for Execution Mode as SQLAgent, the user name will be NT AUTHORITY\SYSTEM. This is the account, which the SQL Agent is configured to use (SQL Agent Service account) which can be changed if required.


Previous
Next

Executing an SSIS package through command line utility and power shell

Using Dtexec command line utility
Open command prompt and use following command to execute the package. Set the value of variable Mode as Dtexec as shown below and execute the command.

Verify the result in the table. There is lot of switches used in the above command and the tricky part here is that all this can be generated without writing even a single line inside the command prompt. Open the Execute package Utility using dtexecUI (as we have seen earlier in executing the package using DtExecUI). After selecting the package source and package name, set the variable’s value as Dtexec. Then click on Command Line tab and copy the command and paste it in command prompt after typing DTEXEC. The command that is to be copied from DtExecUI is shown below:


Using Windows Powershell
Windows powershell can also be used to execute the package in same way we executed the package using command line utility with a very small difference. Open windows powershell and use same command which was used in dtexec command line utility and execute as shown below:

In the above figure there is a message “option set is invalid” and the package does not gets executed (can be verified by checking the result in the table). The only small difference between the commands used in command prompt and powershell is double quote (“) after [User::Mode] as shown in red circle below:

Remove this double quote and add a double quote after the variable value powershell as shown below:
Check the result in the table. A new row with Execution Mode as Powershell is present in the table now.


Previous
Next

Friday, January 15, 2010

Execution Modes of SSIS package in Detail

I wrote a blog on various modes of SSIS package execution few days back. But I did not explain any one of them. So, I thought of giving a detailed explaination of how to execute an SSIS package using various execution modes. To check and verify the result of each execution mode, create a table as:


Now create a simple SSIS package using BIDS. The package will contain a variable named Mode of type string (in the scope of package)and an Execute SQL Task. Use following insert statement as SQL Statement in execute sql task:
INSERT INTO SSISExecutionMode (ExecutionMode)SELECT ?
"?" is parameter which will be mapped to variable (Mode) using Parameter Mapping tab inside the Execute SQL Task Editor. Now the stage is set to start executing the package using various modes and checking the result in table.
Following are the various modes:

Using BIDS
Open the package and set the value for the variable "Mode" as BIDS as shown in the below figure and then execute the package.


Verify the package execution result in the table by issuing a Select statement against the table as: SELECT * FROM SSISExecutionMode
The result will show 1 row in the table with Execution Mode value as BIDS
Using DtExecUI (Execute Package Utility)
Go to Run and enter DtexecUI to open the execute package utility. Select the package source as File System (if the package is deployed on SQL Server, select the SQL Server as Package Source) and click on ellipsis (…) to locate the actual package as shown below:

The path shown in above figure is the actual location of the package. Package can be executed by clicking on execute button but before that set the value for variable "Mode" as "DtexecUI". To set the value of a package variable use "Set Values" tab in the execute package utility as shown below:

Now click the Execute button and check the result in table. This time there will be a new entry in the table with Execution Mode as DtexecUI.

Next

Sunday, January 10, 2010

Create a file using SSIS file system task

I have seen a lot of queries on forums to create an excel file of a particular format and then use it inside a data flow task. File System Task does come to the mind but unfortunately there is no "Create" operation inside File System Task.
But there is a workaround with little bit of stage setting.
Suppose an excel file is to be created on a daily basis and the name of the file should be the current date (20100110, 20100111 etc.)
First it is required to create a template excel file (same as the file required to be created daily). Then a file system task to copy this template file to the destination folder (folder where the new file is to be created). Then use another file system task to rename the copied file with system date.
Step1: Create a template excel file (Sample.xls) in C:\ABC folder
Step2: Create 3 variables (string type and package scoped) named :
Dest with value as :C:\XYZ (folder where new file is to be created)
Final with "Evaluate as Expression" property set as TRUE. then set the
expression as: "C:\\XYZ\\" +REPLACE(SUBSTRING( (DT_WSTR,30)GETDATE(),1,10),"-","")+ ".xls"
Rename with value as : C:\XYZ\Sample.xls
Step3: Take a File System Task and open the File System Task editor.
Select Operation as "Copy File"
Set IsDestination path variable to TRUE and select Dest from drop down box as variable.
Keep IsSourcePath variable as FALSE and create a connecion manager for C:\ABC\Sample.xls
Step4: Take one more File System Task and open the File System Task editor.
Select Operation as "Rename File"
Set IsDestination path variable to TRUE and select Final from drop down box as variable.
Keep IsSourcePath variable as TRUE and select Rename from drop down box as variable.

Select the 2nd File System Task, hit F4 (to go to its properties) and set "Delay Validation" as TRUE. The new excel file with current date as its name can be verified in folder C:\XYZ

Sunday, December 20, 2009

Various ways to execute an SSIS package

When we develop a package, we execute it throuh Business Intelligence Development Studio (BIDS), for testing the package functionality. Once the package is developed and signalled green for a proper intended behavior we deploy it and then scedule it and we are done as a developer. But there are some other ways also apart from BIDS and SQL Agent Job, that can be used to execute a package.
Let's see how many different ways we can execute an SSIS package in:?
1. Using Dtexec utility from command prompt or DOS prompt
2. Using Dtexec utility from powershell or DOS prompt
3. Using DtexecUI also known as Execute Package Utility
4. Using code (C# or VB.Net)
5. Using a batch file and schedult it through Task scheduler
6. Using sp_start_job procedure to execute a sql agent job
7. Using xp_cmdshell to execute a package deployed in MSDB database or from File System
8. Using BIDS
9. Using SQL Agent job

To know how to use all of the aforesaid execution modes, please check my blog

Saturday, December 12, 2009

Executing a task on failure of other tasks in SSIS

I saw a query on SSIS MSDN forum regarding sending a mail when any 1 of the 2 specific task fails at control flow. The way Send Mail Task was attached to those 2 tasks, using Preednce Cnstraint for Failure, was looking absolutely fine but the Send Mail Task was not geting executed on failure of any one of the other two tasks. In fact there was a small mistake in the configuration of precdence constraint and thats why thought of putting it here.
I will try to explain the scenario using three simpe Script tasks. This is how they are connected to each other using precedence constraint.
ScriptA and ScriptB are connected to ScriptC using Precedence constraint for Value as Failure in Precedence Constraint Editor as shown here

Now open the Script editor for ScriptA and change the default code as
Dts.TaskResult = Dts.Results.Failure Now let's execute the package. We will see that ScriptA will turn RED but the ScriptC will not execute. Try to configure ScriptA for success and ScriptB for failure by changing the default code and re-execute the package. Again we will find ScriptC not getting executed. (Why??.. we configured the precedence constraint for Failure.) Okay, lets open the precedence constraint editor and select the radio button "Logical OR". The appearance of the constraint at control flow will change and looks like
Lets execute the package again. This time ScriptC will execute if any one of ScriptA and ScriptB are configured to fail. The key was to change the default selection from Logical AND to Logical OR. Logical AND means both the constraints shoud be true (means both the Taks, ScriptA and ScriptB should fail which is not possible becasue ScriptB will execute only when ScriptA completes successfully) while Logical OR means any one of the two constraint should be true.

Lets configure the constraint between ScriptA and ScriptB to "Completion" and configure both the tasks to fail and execute the package.Also, select Logical AND for the precedence constraint between ScriptA and ScriptC. This time ScriptC should be excuted. This is how the control flow looks after execting the package

Friday, December 4, 2009

Dynamic lookup query in SSIS 2008

In SSIS 2008, lookup component has undergone a significant amount of change. Now we can parameterize the lookup query in Full Cache Mode which was not possible in SSIS 2005. Let’s see how to use dynamic lookup behavior in SSIS 2008.

Scenario:Record is a table having stats about the football players and Detail is the table having information about various players. Information is the table which is created to have consolidated information of all the players.We want to pull the data from Record and Details and push it into Information table for the players of a particular country.
This is how Detail table looks:

This is how Record table looks:


So our approach would be to take Record as Source and Detail as lookup table. Earlier we were unable to parameterize the lookup query in Full Cache mode. But in SSIS 2008, we can do that and I am going to use this enhancement while doing the lookup on Detail table.
Create 2 package scoped variables: Country and SQL (both of type string). Country is the variable used to parameterize the lookup query and SQL is the variable which is used to create the lookup query (not clear!! Well, I will explain the use of this variable when the context will come). So this is what Data Flow and the variable window look like:



Source is Record table and Lookup is using Detail table. This is how the new lookup transformation editor looks like
Click on connection and select the appropriate connection manager and write a query as:
SELECT * FROM Detail
Then click on Columns and complete the lookup editor. Then take an OLEDB destination and select the Information table as the destination and do the column mapping. So the data flow task is complete. But we have not yet parameterized our lookup query. So let’s do that (Yes, there is no parameter button in the lookup editor). Go to variable and give it a default value of Brazil. Go to SQL variable and set its “evaluate as expression” property as True. Then set an expression for this variable using Country variable as:
"Select * From Detail Where Country = '" + @[User::Country] + "'"
If you remember, I have created variable SQL to frame the lookup query. Now, we will use this SQL variable as lookup query. Select the data flow task and go to its properties. Click on the ellipsis (…) against Expressions and select the property [LookupName].[SqlCommand] as shown
Hit OK and done. Execute the package and you will see that lookup component has cached only those records for which Country is Brazil. In my Detail table there are 4 rows for Brazil so lookup has brought only 4 rows in memory instead of all the rows from Detail table. After executing the package, go to Execution Results tab to check how many rows are brought in memory by lookup component. In my package, name of lookup component is LKP_PLAYER_DETAILS and you can see that number of rows cached are 4 which is equal to number of rows for Brazil.


Thursday, November 26, 2009

Dynamic connection in SSIS using Expressions

Here is the Control Flow: Scenario:
We have a set of text files that contains information about players of English Premier League. There is one text file for each football club. We want to push all this infomration in a Excel Workbook. There are 2 ways of pushing the data into excel workbook. Either push all the text files information into a sngle work sheet in a workbook OR create a work sheet for each text file and then push the data in corresponding work sheet.
Now, I have 3 text files in F:\MyStuff\EPL folder. All these 3 text files store name of a player, his country and number of goals scored. So in total there are 3 columns in all thes 3 text files.
I have a excel workbook EPL.xls in F:\MyStuff\EPL folder and all the records are to be pushed into this workbook. By default there are some work sheets (Sheet1,Sheet2..). Keep only one sheet and delete others. Rename the only sheet as SAMPLE and add three columns to it: NAME,COUNTRY,GOALS (Why to add columns??..Well, I will explain it later). Declare 3 variables FileName- to capture the name of the text file inside for each loop, SheetName- is used to create the name for excel sheet to be created and SQL- is used to frame a Create Table Statement for creating the excel sheet in workbok
Exercise1: Lets bring all the information from 3 text files into one WorkSheet. Grab a For Each Loop Container and configure it for the text file as shown below
Then click on the variable mappings and select the variable FileName as shown below
Take a Data Flow Task (shown as DFT_ALL_IN_ONE in the control flow) inside the For Each Loop container. Take a flat file source inside Data Flow Task and double click it to open the Flat File Source Editor. Click on New to create a flat file connection manager which points towards one of the text files in F:\MyStuff\EPL folder and then complete the flat file source configuration hitting Columns tab and then OK. Now we are ready with Flat file Source. Next step is to take a Excel Destination. Create an excel connection manager (EXCEL_SINGLE) which points towards the excel workbook. Then configure the excel destinaitonas shown below
Use data access mode as Table or View and select the sheet SAMPLE$. If you remember we have added three columns to the sheet SAMPLE in the destinaiton excel workbook. We added 3 column because the text files contain three columns and we have to take those columns from text files to the excel work sheet. Then click on Mappings tab in the left pane and complete the column mappings between Input column and Destination column. If you get a small red X mark on Excel Destination after completing the configuration, either use a Data Conversion component after Flat File Source or go to Advanced Editor of Flat file source (by rt clicking the flat file source) and select the Input and Output properties. Then select Output Columns and change the datatype as required.

Exercise2: Lets create a work sheet for each text file and move the data from each text file to a different excel work sheet. In the above control flow, there is a execute sql task (EST_CREATE_SHEET) which is responsible for creating the worksheets in a work book. So take a execute sql task inside the for each loop and select the Connection type as EXCEL. Then select the excel connection manager created as a part of exercise1 from the drop down box as Connection. Select SQL Source type as variable and select source variable as SQL. Execute SQL Task editor will look like: Now lets see what this SQL variable is all about?SQL variable is used to store the CREATE TABLE statement which will create excel work sheets inside the excwl workbook. Select the variable SQL and set an expression for it as:
"CREATE TABLE " + @[User::FileName] + " (Name VARCHAR(40),Country VARCHAR(40),Goals INT)"
Thisexpression will create a work sheet at each iteration of the for each loop with the name as the name of the text file which gets captured in FileName variable.Aftre this take a Data Flow Task and configure it as the first data flow task was configured only difference is the data access mode in Excel Destination. This time access mode will be Table name or view name variable as shown below: SheetName is the variable that will store the excel worksheet name where data is to be transfered. Select the variable SheetName and set its "Evaluate as Expression" property to true. Write an expression as: @[User::FileName] + "$"
Execute the package and check the results in excel workbook.

Friday, November 20, 2009

Loop through excel sheets using SSIS



Control flow of the package once you complete Step1 to Step6 will look like:
Scenario:
I have 2 excel workbooks EPL.xls (with 3 excel sheets inside) and SPANISH
.xls (with 2excel sheets inside).All the 5 sheets have same number of columns with same name as well. I want to design a SSIS package to read all these 5 sheets and put all the records in a text file.
Declare 2 string variables ExcelPath and ExcelSheet in the scope of package.


Step1: Take for each loop which will loop through all the excel workbooks inside a particular folder. Edit for each loop as shown in the figure and click on Collection in left pane. My excel workbooks are in F:\MyStuff folder so I have used the location of the workbooks in the Folder option. Since I want to loop trough al the excel files, I have given *.xls in the Files option.

Step2:
Capture the excel workbook name in a string variable. I have defined a variable ExcelPath of type string. Click on variable mappings and select the ExcelPath variable from the drop down box with Index as 0 as shown in the following figure:
Step3:
Create an ADO.NET connection manager. Right click on the connection manager’s pane and select New ADO.NET Connection.Then click on New in Configure ADO.NET Connection Manager window and configure the connection manager as shown in the figure and click OK
Browse to an excel workbook in MyStuff folder as shown in the following figure:
Click All in the left pane and enter Excel 8.0 in Extended Properties and then click Test Connection to verify if the connection is successful. Now an ADO.NET connection manager is created with name as EPL. Go to properties of the EPL and click the ellipsis (…) against the Expressions.In the Property Expression Editor, select Connection String and set the expression as following:
"Data Source=" + @[User::ExcelPath] + ";Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;"
Step4: Now take one more For each loop inside the previous one and configure it as shown in the following figure:
Go to variable mappings and select ExcelSheet variable to capture the sheet name and set Index as 2.

Step5:
EPL.xls has 3 work-sheets : MANCHESTERUNITED,CHELSEA AND LIVERPOOL. Go to the variable ExcelSheet and set its value as CHELSEA$.Drag a Data Flow Task inside the inner for each loop. Take a Excel Source inside Data Flow Task and double click the excel source. Click New to create an excel connection manager using a valid excel file which has same structure as the excel files in F:\MyStuff folder. In this example I am taking EPL.xls which is sitting in F:\MyStuff folder. Check the "First row has column names" check box and click OK. Select Data Access Mode as Table Name or Vie Name variable and select the ExcelSheet variable from the "Variable Name" drop down box .
Click on Columns in Excel Source edotor to verify the column names and then click OK. Go to the properties of Excel Connection Manager and use the ellipsis (…) against the expressions to set the Connection String property using following expression:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @[User::ExcelPath]+";Extended Properties=\"" + "Excel 8.0;HDR=YES\"" + ";"

Step6:
I will capture all the records from the sheets into one text file. I have created a text file Information.txt. Then grab a Flat File Destination and double click on it to open the editor. Uncheck the "Overwrite data in File" option and click New to create a flat file connection manager. Verify that the Delimited radio button is selected and then click OK. Configure the Flat File connection manager editor as shown in the following figure:
Click on columns then mappings and click OK. Now we are ready to execute the package.