Pages

Showing posts with label SSIS. Show all posts
Showing posts with label SSIS. Show all posts

Tuesday, November 20, 2012

Sending HTML formatted email in SQL Server using the SSIS Script Task


Sending HTML formatted email in SQL Server using the SSIS Script Task

I will start my discussion on using the Script Task to send email (both non-HTML and HTML formatted) with an example. First I will create a database table (MailsToBeSent) which will hold the information about the emails which are to be sent by the Script Task and then insert a few records in this table. Next I will create a stored procedure to retrieve the records from the above created tables.
So here is the script for creating these database objects.
--Create a table to store mails to be sent details
CREATE TABLE MailsToBeSent
(
[MailID] INT PRIMARY KEY,
[From] VARCHAR(200),
[TO] VARCHAR(200),
[CC] VARCHAR(200),
[BCC] VARCHAR(200),
[Subject] VARCHAR(200),
[Body] VARCHAR(MAX),
[IsHTMLFormat] BIT,
[Priority] CHAR(1)
) 
GO  
--Insert a non-HTML mail details to be sent
INSERT INTO MailsToBeSent([MailID], [From], [TO], [CC], [BCC], [Subject], [Body],[IsHTMLFormat], [Priority])
VALUES(1, 'arshad@gmail.com', 'arshad@gmail.com', 'arshad@gmail.com;ali@gmail.com','', 
'Sending Non-HTML Mail Using Script Task', 'This Non-HTML mail has been sent using SSIS Script task.', 0, 'L')
GO  
--Insert a HTML formatted mail details to be sent
INSERT INTO MailsToBeSent([MailID], [From], [TO], [CC], [BCC], [Subject], [Body],[IsHTMLFormat], [Priority])
VALUES(2, 'arshad@gmail.com', 'arshad@gmail.com', 'arshad@gmail.com;ali@gmail.com','', 
'Sending HTML formatted Mail Using Script Task', 
'This <strong><span style="font-size:130%;color:#006600;">HTML formatted</span></strong> 
mail has been sent using <em><span style="color:#ff6600;">SSIS Script task</span></em>.', 
1, 'H')
GO

--Create a procedure to retrieve all the records 
--from MailsToBeSent table to send mails
CREATE PROCEDURE GetMailsToBeSent
AS
BEGIN
SELECT [MailID], [From], [TO], [CC], [BCC], [Subject], 
[Body], [IsHTMLFormat], [Priority]
FROM MailsToBeSent
END
GO  
EXEC GetMailsToBeSent
GO
Once you are done with the database object creation, let’s move on to create a package with Script Task to send emails.

Create a new project of Integration Services type in the Business Intelligence Development Studio. Drag a Script Task from the toolbox and drop it onto the Control Flow area of the Designer interface, right click on Script Task component and then select Edit, a screen similar to one as given below will come up. This is a screen shot from SSIS 2008. If you are still using SSIS 2005 it will say "Design Script..." instead of "Edit Script...".
 
ssis script task
On the Script page of “Script Task Editor” click on “Edit Script” button, it will bring up VSTA environment (On SSIS 2005 it’s VSA environment) for writing .Net code for sending emails.
Copy the code from the below tables and paste it in the VSA/VSTA code editor. There are two sets of code one for 2005 and one for 2008, so make sure you use the right version based on your version of Business Intelligence Development Studio, not the version of SQL Server you are connecting to.  Because of changes in the scripting environment between SQL Server 2005 and 2008, there would is a slight change in the code that's why I am providing the below separate code to be used on SQL Server 2005 and on SQL Server 2008. If you are running the below code in your Script Task in SSIS 2005 environment, you may need to reference the System.XML.dll. By default it is included and referenced dll in SSIS 2008, so you would not have to worry if you are using it on SSIS 2008.
Here are the objects that are referenced with the System.XML highlighted below.
ssis script task system.xml
Please note you need to change the connection string in the code pointing to the server and database where you have created the above database objects and also change the SMTP server name which will be used to send emails.  The two lines of code are as follows:
ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
mySmtpClient = New SmtpClient("smtpserver")
Also, I have commented out the section that allows you to send emails using authentication to your mail server.  So if you want to use a user and password this can be supplied as well.
Script : VB .Net Code for Script Task for SQL Server 2005
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Imports System.Net.Mail
Imports System.Data.SqlClient
Imports System.Xml
Public Class ScriptMain
    ' The execution engine calls this method when the task executes.
    ' To access the object model, use the Dts object. Connections, variables, events,
    ' and logging features are available as static members of the Dts class.
    ' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    ' 
    ' To open Code and Text Editor Help, press F1.
    ' To open Object Browser, press Ctrl+Alt+J.
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
        Dim mySmtpClient As SmtpClient
        Dim ConnString As String
        ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
        Try
            Dim SqlQuery As String = "GetMailsToBeSent"
            Using conn As New SqlConnection(ConnString)
                conn.Open()
                Dim comm As New SqlCommand(SqlQuery, conn)
                comm.CommandType = CommandType.StoredProcedure
                Dim adap As New SqlDataAdapter(comm)
                Dim ds As New DataSet()
                adap.Fill(ds)
                If ds.Tables(0).Rows.Count > 0 Then
                    Dim intCount As Integer
                    Dim intCCCounter As Integer
                    Dim intBCCCounter As Integer
                    For intCount = 0 To ds.Tables(0).Rows.Count - 1
                        'Create an instance of MailMessage class and pass "From EmailID" and "To EmailID" to the constructor
                        '"To" list can accept multiple email address deliminated by comma
                        Using myMessage As New MailMessage(ds.Tables(0).Rows(intCount).Item("From").ToString(), Replace(ds.Tables(0).Rows(intCount).Item("To").ToString(), ";", ","))
                            'CC List
                            'MailMessage.CC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop for multiple address
                            'Also you can create a MailAddressCollection first, add all the CC email address to it and finally assign it to MailMessage.CC property
                            Dim CCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Cc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","), ",")
                                    For intCCCounter = 0 To strEmails.Length - 1
                                        CCAddressList = New MailAddress(strEmails(intCCCounter))
                                        myMessage.CC.Add(CCAddressList)
                                    Next
                                Else
                                    CCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","))
                                    myMessage.CC.Add(CCAddressList)
                                End If
                            End If
                            'BCC List
                            'MailMessage.BCC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop below for multiple address
                            'Also you can create a MailAddressCollection first, add all the BCC email address to it and finally assign it to MailMessage.BCC property
                            Dim BCCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","), ",")
                                    For intBCCCounter = 0 To strEmails.Length - 1
                                        BCCAddressList = New MailAddress(strEmails(intBCCCounter))
                                        myMessage.Bcc.Add(BCCAddressList)
                                    Next
                                Else
                                    BCCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","))
                                    myMessage.Bcc.Add(BCCAddressList)
                                End If
                            End If
                            myMessage.Subject = ds.Tables(0).Rows(intCount).Item("Subject").ToString()
                            myMessage.Body = ds.Tables(0).Rows(intCount).Item("Body").ToString()
                            If ds.Tables(0).Rows(intCount).Item("IsHTMLFormat").ToString().ToUpper() = "TRUE" Then
                                myMessage.IsBodyHtml = True
                            Else
                                myMessage.IsBodyHtml = False
                            End If
                            If ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "L" Then
                                myMessage.Priority = Mail.MailPriority.Low
                            ElseIf ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "H" Then
                                myMessage.Priority = Mail.MailPriority.High
                            Else
                                myMessage.Priority = Mail.MailPriority.Normal
                            End If
                            'To be used for sending attachements
                            'myMessage.Attachments.Add(New Attachment("c:\example1.txt"))
                            'myMessage.Attachments.Add(New Attachment("c:\example2.txt"))
                            mySmtpClient = New SmtpClient("smtpserver")
                            'You can set the SMTP port number if it is not listening on default port
                            'mySmtpClient.Port = 26
                            'The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running.
                            mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
                            'If you don't want to use windows authentication to connect to your SMTP host and want to specify a different username and password, you can then use NetworkCredential class as shown below
                            'The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos.
                            'mySmtpClient.Credentials = New NetworkCredential("arshad", "abcd", "corpnet")
                            mySmtpClient.Send(myMessage)
                        End Using
                    Next
                End If
                conn.Close()
            End Using
        Catch E As Exception
            Dts.Events.FireError(-1, "Failure in Script Task while sending mails.", E.Message.ToString(), "", 0)
            Dts.TaskResult = ScriptResults.Failure
        End Try
        Dts.TaskResult = ScriptResults.Success
    End Sub
End Class
Script : VB .Net Code for Script Task for SQL Server 2008
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Imports System.Net.Mail
Imports System.Data.SqlClient
Imports System.Xml
 _
 _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
        Dim mySmtpClient As SmtpClient
        Dim ConnString As String
        ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
        Try
            Dim SqlQuery As String = "GetMailsToBeSent"
            Using conn As New SqlConnection(ConnString)
                conn.Open()
                Dim comm As New SqlCommand(SqlQuery, conn)
                comm.CommandType = CommandType.StoredProcedure
                Dim adap As New SqlDataAdapter(comm)
                Dim ds As New DataSet()
                adap.Fill(ds)
                If ds.Tables(0).Rows.Count > 0 Then
                    Dim intCount As Integer
                    Dim intCCCounter As Integer
                    Dim intBCCCounter As Integer
                    For intCount = 0 To ds.Tables(0).Rows.Count - 1
                        'Create an instance of MailMessage class and pass "From EmailID" and "To EmailID" to the constructor
                        '"To" list can accept multiple email address deliminated by comma
                        Using myMessage As New MailMessage(ds.Tables(0).Rows(intCount).Item("From").ToString(), Replace(ds.Tables(0).Rows(intCount).Item("To").ToString(), ";", ","))
                            'CC List
                            'MailMessage.CC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop for multiple address
                            'Also you can create a MailAddressCollection first, add all the CC email address to it and finally assign it to MailMessage.CC property
                            Dim CCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Cc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","), ",")
                                    For intCCCounter = 0 To strEmails.Length - 1
                                        CCAddressList = New MailAddress(strEmails(intCCCounter))
                                        myMessage.CC.Add(CCAddressList)
                                    Next
                                Else
                                    CCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","))
                                    myMessage.CC.Add(CCAddressList)
                                End If
                            End If
                            'BCC List
                            'MailMessage.BCC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop below for multiple address
                            'Also you can create a MailAddressCollection first, add all the BCC email address to it and finally assign it to MailMessage.BCC property
                            Dim BCCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","), ",")
                                    For intBCCCounter = 0 To strEmails.Length - 1
                                        BCCAddressList = New MailAddress(strEmails(intBCCCounter))
                                        myMessage.Bcc.Add(BCCAddressList)
                                    Next
                                Else
                                    BCCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","))
                                    myMessage.Bcc.Add(BCCAddressList)
                                End If
                            End If
                            myMessage.Subject = ds.Tables(0).Rows(intCount).Item("Subject").ToString()
                            myMessage.Body = ds.Tables(0).Rows(intCount).Item("Body").ToString()
                            If ds.Tables(0).Rows(intCount).Item("IsHTMLFormat").ToString().ToUpper() = "TRUE" Then
                                myMessage.IsBodyHtml = True
                            Else
                                myMessage.IsBodyHtml = False
                            End If
                            If ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "L" Then
                                myMessage.Priority = Mail.MailPriority.Low
                            ElseIf ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "H" Then
                                myMessage.Priority = Mail.MailPriority.High
                            Else
                                myMessage.Priority = Mail.MailPriority.Normal
                            End If
                            'To be used for sending attachements
                            'myMessage.Attachments.Add(New Attachment("c:\example1.txt"))
                            'myMessage.Attachments.Add(New Attachment("c:\example2.txt"))
                            mySmtpClient = New SmtpClient("smtpserver")
                            'You can set the SMTP port number if it is not listening on default port
                            'mySmtpClient.Port = 26
                            'The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running.
                            mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
                            'If you don't want to use windows authentication to connect to your SMTP host and want to specify a different username and password, you can then use NetworkCredential class as shown below
                            'The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos.
                            'mySmtpClient.Credentials = New NetworkCredential("arshad", "abcd", "corpnet")
                            mySmtpClient.Send(myMessage)
                        End Using
                    Next
                End If
                conn.Close()
            End Using
        Catch E As Exception
            Dts.Events.FireError(-1, "Failure in Script Task while sending mails.", E.Message.ToString(), "", 0)
            Dts.TaskResult = ScriptResults.Failure
        End Try
        Dts.TaskResult = ScriptResults.Success
    End Sub
End Class
You should make sure you properly dispose of the instance of MailMessage class especially if you are sending attachments with the email otherwise you will end up having your files locked by Windows OS and you will not be able to delete them. The easiest way to avoid overhead of disposing of the unused objects is to use the USING statement and write your code inside its block, similar to the way it has been done in the above code.
So now for the execution of the above created package, two emails are sent to the intended audience as shown below. As expected the first email (MailMessage.IsBodyHtml = False) is non-HTML email whereas the second email (MailMessage.IsBodyHtml = True) is HTML formatted, look at color in the message body.

  • If you are running the above code in your Script Task in SSIS 2005 environment, you may need to make reference to System.Xml.dll. By default it is included and referenced dll in SSIS 2008, so you would not have to worry if you are using it on SSIS 2008.
  • You need to reference System.Net.Mail namespace in your code which contains MailMessage and SmtpClient classes which are required for sending emails.
  • There are three differences to note here between SSIS 2005 and SSIS 2008 in terms of the Script Task.
    • Now you have two language options to write your code i.e. Visual Basic .Net and C# .Net in SSIS 2008 whereas you had only one language option in SSIS 2005.
    • The scripting environment in SSIS 2008 is VSTA and it is VSA in SSIS 2005. It means almost full .Net capabilities in SSIS
    • In SSIS 2008, in Script Task Editor Dialog box, the Script page has got preference over other pages and is the first page in list on the left side, it means it saves one more click to reach to your development environment to write your code.

Analysis Services Processing-ssis


Analysis Services Processing Task in SQL Server Integration Services SSIS

The Analysis Services Processing Task allows you to process dimensions, measure group partitions, and mining models in an SSIS package.  While you can process all of these objects at one time, you can also select a subset of these objects to be processed as well.  For example you may update certain dimension and fact tables in your data warehouse on a periodic basis by running an SSIS package.  As a final step in the SSIS package, you would like to process just the dimensions and measure group partitions that use those data warehouse tables as their data source.  The Analysis Services Processing Task allows you to do that.
In this tip we will walk through the steps to use the Analysis Services Processing Task in an SSIS package.   We'll create a sample package that will process a dimension and a measure group partition in the Adventure Works DW Analysis Services database that comes with SQL Server 2005.   Our hypothetical scenario is that we run an SSIS package to update the Product and Currency Rate tables in our data warehouse on a daily basis.  We would like to add a step to the SSIS package to process the Product dimension and the Currency Rate fact table, thereby updating the information available in our SQL Server Analysis Services cube. 
Create the Sample SSIS Package
To begin launch Business Intelligence Development Studio (BIDS) from the Microsoft SQL Server 2005 program group and create a new Integration Services project.   An SSIS package named Package.dtsx will be created automatically and added to the project.  Rename the package to SSASProcessingTask_Demo.dtsx then perform the following steps on the SSIS package: 
Step 1: Add a Connection Manager for the SSAS server.  Right click in the Connection Managers area and select New Analysis Services Connection from the context menu.  Accept the defaults in the dialog to connect to the local SSAS Server (or edit as appropriate if you want to connect to an SSAS Server on another machine):
Step 2: Drag and drop the Analysis Services Processing Task from the Toolbox onto the Control Flow of the SSIS package.  Edit the Analysis Services Processing Task; select the connection manager defined in step 1 above and click the Add button to select the objects to be processed:
The Process Options selected work as follows:
  • Process Incremental on a measure group partition is used to load just new rows from the fact table.  It requires additional settings which we will complete in the next step.
  • Process Update for a dimension will update the dimension with any inserts, updates or deletes from the data warehouse.
Step 3: Click the Configure hyperlink in the Currency_Rates row shown in step 2 above.    Since we have selected Process Incremental as the Process Option we need to either specify a table or view to load the new fact rows from or specify a query; we'll specify a query and assume that the stg_FactCurrencyRate table is populated with just the new fact rows to be added to the measure group partition.

  • If you don't already have the AdventureWorks SSAS sample projects and databases available, you can download them here to get the starting point for this tip.  Click the AdventureWorksBICI.msi link.  Also click on the Release Notes link for the details on attaching the relational database.  The default install location for the project is C:\Program Files\Microsoft SQL Server\90\Tools\Samples\AdventureWorks Analysis Services Project; you will see Enterprise and Standard folders.  We used the project in the Enterprise folder.
  • Take a look at the technical article Analysis Services 2005 Processing Architecture for an in-depth discussion of the processing options available for cubes, dimensions, and mining models.

Null -SSIS packages using scripting


NULL Defense to your SSIS packages using scripting

For the discussion of the problem in question, we will leverage the same package that we built in the first part of the NULL Defense Series.
In order to simulate the issue, create another table "NULLDefenseReplica" in the "TestDB" database. This table should have the same definition / structure as that of the NULLDefense table. Basically we are creating a destination table that we would use to insert records from the NULLDefense table which we are using as a source in our package.
Create a new ADO.Net connection to the "TestDB" database and name it MyADOConn.
Add a Script Transformation to the package, select the type as "Destination", and name it "Insert Records". Add the datapath from ValidRecords multicast output and join it to this Script Transform. Now configure the Script component as follows.
Rename the input stream from "Input 0" to "MyInputStream".
NULL values in data is one of the most common reasons that can make your SSIS package fail
Select all the columns for the available input columns.
Create a new ADO.Net connection to the "TestDB" database and name it MyADOConn
Add a connection on the connections page, select the ADO.NET Connection we just created and name it ADOTestDBConnection as shown below.
select the ADO.NET Connection we just created
Now we need to configure this script transform to insert records into our NULLDefenseReplica table. I will not go into the details of explaining the entire code, but if you would like to learn more you can read about it on MSDN BOL. Add the code as can be seen in the below. You can download it from here.
 configure this script transform to insert records into our NULLDefenseReplica table
Execute the package now and it should execute successfully and insert one record in the NULLDefenseReplica table.
nsert one record in the NULLDefenseReplica table
Now for testing, remove the Script destination from the "Valid Records" multicast transformation and add the output from "Invalid Records" multicast to the input of the script transformation. Execute the package and you should encounter an error as shown in the picture below. The reason for this is what Microsoft states in MSDN BOL as "If the Script component contains a script that tries to read the value of a column that is NULL, the Script component fails when you run the package. We recommend that your script use the IsNull method to determine whether the column is NULL before trying to read the column value".
remove the Script destination from the "Valid Records" multicast transformation and add the output from "Invalid Records" multicast to the input of the script transformation
To build our NULL Defense for this problem there are two parts to this solution. One part is validating if the field in the row being processed contains a null value and the second part is assigning NULL or valid values to parameters based on values found in the fields. Edit the script and change the code as shown below and execute the package. The package should execute successfully.
To build our NULL Defense for this problem there are two parts to this solution


we have successfully built a NULL Defense for one of the most common scenarios in a Script transformation where NULL values in data can make your package fail
So finally we have successfully built a NULL Defense for one of the most common scenarios in a Script transformation where NULL values in data can make your package fail.

NULL Management-SSIS packages


NULL defense for dates in SSIS packages

In order to create a test bed for our NULL Defense series, create a new database ( name it something like TestDB ) which we will use for simulating problems and developing solutions.

Create a new table called NULLDefense and populate it with data exactly as shown in the picture below. To keep the focus on the problem, we would keep the structure simple, but inclined towards the problem for which we will create our NULL Defense.



Now follow the steps below to create the SSIS package which will simulate the problem in question.
  • Create a new SSIS Project
  • Add a new package to it and name it "NULLDefense".
  • Add a new Data Flow Task to the package.
  • Add an OLE DB Source and name it "NULLDefense - TestDB".
  • Edit the OLE DB Source and connect it to the table we just created.
  • Add a Conditional Split transformation and name it "Split valid and invalid rec". The expected use of this transformation is to split records which contain dates and records which do not contain dates. Edit this transformation as shown in the picture below and also make sure you change the Default output name to "Valid Records" as shown below.


Since this is only for demonstration, we are not going to waste time inserting these records, so we will just use two Multicasts for the destinations to analyze the number of records going to each destination.
  • Add a Multicast transform and name this "Invalid Records".  This should be tied to the "Dates Unavailable" output from the Conditional Split.
  • Add another Multicast transform and name this "Valid Records" and this should be tied to the "Valid Dates" output from the Conditional Split.
After you have completed these steps, your package should look something like the below picture.



Now if you take a look again at the data we have inserted into our table, we should have two records on the invalid output side and one record on the valid side as there are two records which do not have dates. The reason why we inserted a record with NULL and one record with '' is this is one of the scenarios that you will find in real life projects. Applications insert data into OLTP systems and many times application developers insert data using '' as a placeholder for no date instead of using a constant for NULL from the data access libraries (something like SQLDBNULL) which sends a NULL value to the database instead of a blank value. But from a user or business point of view any date that is not available is NULL, though blank and NULL might carry a different meaning and behavior from a technical standpoint.

Execute the package and you will find two records on the valid side and only one on the invalid side. You would find the same result even if you put a condition using the LEN function to measure the length of the value in the DOB field.



Go back to SSMS and view the data in the NULLDefense table we just created and you will find the reason for this. Whenever a blank value is entered inside a datetime field, when you run a query it will return a default value of "1900-01-01 00:00:00.000" as can be seen in the below picture.



We now move towards the solution for this.

I would not consider any options of making changes at the database level as we might not have the liberty of changing anything for our ETL solution as many other applications might be depending on the existing settings of the database.

Coming to the next alternative, we can place additional checks at the database level to ensure that the value is neither NULL nor the default value, but this kind of solution cannot be considered for a real-time solution as there might be numerous functions and conditions operating on this field and everywhere a dual check or replacement function would be required to fix this issue.

Finally, the option that I recommend is to bring uniformity in perception of NULL to our package and feeding only data that is either NULL or non-NULL to the package. This can be done through a very simple step at the database level itself, without changing any existing database settings, values or logic.

For our test package, just create a new "view" as shown in the picture below where we replace the default value with NULL.



Now change the connection of the source in our package to this view and execute the package. The results should now be as expected, which can be seen in the below figure.



Datetime is one special datatype which can trick you with NULLs and we just developed a defense against NULL date values.
 Steps
  • Try to size the efforts that you would need to patch this NULL or blank issue of dates if you would be fixing this in your existing SSIS packages.
  • Implement this solution and compare the benefit and issues of implementing it at the database level instead of at the package level.

Wednesday, January 4, 2012

Have you used the ExecutionValue and ExecValueariable properties?


The ExecutionValue execution value property and it’s friend ExecValueVariable are a much undervalued feature of SSIS, and many people I talk to are not even aware of their existence, so I thought I’d try and raise their profile a bit.
The ExecutionValue property is defined on the base object Task, so all tasks have it available, but it is up to the task developer to do something useful with it. The basic idea behind it is that it allows the task to return something useful and interesting about what it has performed, in addition to the standard success or failure result. The best example perhaps is the Execute SQL Task which uses the ExecutionValue property to return the number of rows affected by the SQL statement(s). This is a very useful feature, something people often want to capture into a variable, and start using the result set options to do. Unfortunately we cannot read the value of a task property at runtime from within a SSIS package, so the ExecutionValue property on its own is a bit of a let down, but enter the ExecValueVariable and we have the perfect marriage.
The ExecValueVariable is another property exposed through the task (TaskHost), which lets us select a SSIS package variable. What happens now is that when the task sets the ExecutionValue, the interesting value is copied into the variable we set on the ExecValueVariable property, and a variable is something we can access and do something with. So put simply if the ExecutionValue property value is of interest, make sure you create yourself a package variable and set the name as the ExecValueVariable. Have  look at the 3 step guide below:
1 Configure your task as normal, for example the Execute SQL Task, which here calls a stored procedure to do some updates.
Execute SQL Task Editor
2 Create variable of a suitable type to match the ExecutionValue, an integer is used to match the result we want to capture, the number of rows.
Adding a package variable
3 Set the ExecValueVariable for the task, just select the variable we created in step 2. You need to do this in Properties grid for the task (Short-cut key, select the task and press F4)
Setting the ExecValueVariable property
Now when we execute the sample task above, our variable UpdateQueueRowCount will get the number of rows we updated in our Execute SQL Task.
I’ve tried to collate a list of tasks that return something useful via the ExecutionValue and ExecValueVariable mechanism, but the documentation isn’t always great.
TaskExecutionValue Description
Execute SQL TaskReturns the number of rows affected by the SQL statement or statements.
File System TaskReturns the number of successful operations performed by the task.
File Watcher TaskReturns the full path of the file found
Transfer Error Messages TaskReturns the number of error messages that have been transferred
Transfer Jobs TaskReturns the number of jobs that are transferred
Transfer Logins TaskReturns the number of logins transferred
Transfer Master Stored Procedures TaskReturns the number of stored procedures transferred
Transfer SQL Server Objects TaskReturns the number of objects transferred
WMI Data Reader TaskReturns an object that contains the results of the task.
Not exactly clear, but I assume it depends on the WMI query used.

Expression Date Functions


Date Parts

Expressions support a range of date related functions such as DATEADD, with the same basic syntax to that found in T-SQL. Whilst the familiarity is very helpful, the difference that catches me out is the format of date part which must be quoted.
T-SQL allows this:
 DATEADD(n, -10, GETDATE())
 DATEADD(mi, -10, GETDATE())
 DATEADD(minute, -10, GETDATE())
The SSIS equivalent is:
 DATEADD("n", -10, GETDATE())
 DATEADD("mi", -10, GETDATE())
 DATEADD("minute", -10, GETDATE())
Related functions that use the same date part tokens -
  • DATEADD
  • DATEDIFF
  • DATEPART

Month Name Expressions

Here are some month name expressions, just waiting for a DATENAME function.
Get the month name, for the column RowDate:
 (MONTH(RowDate) == 1 ? "January" : MONTH(RowDate) == 2 ? "February" : MONTH(RowDate) == 3 ? "March" : 
  MONTH(RowDate) == 4 ? "April" : MONTH(RowDate) == 5 ? "May" : MONTH(RowDate) == 6 ? "June" : 
  MONTH(RowDate) == 7 ? "July" : MONTH(RowDate) == 8 ? "August" : MONTH(RowDate) == 9 ? "September" : 
  MONTH(RowDate) == 10 ? "October" : MONTH(RowDate) == 11 ? "November" : 
  MONTH(RowDate) == 12 ? "December" : "InvalidMonth")
Get formatted month and year, mmm (yyyy), from the column RowDate:
 (MONTH(RowDate) == 1 ? "Jan" : MONTH(RowDate) == 2 ? "Feb" : MONTH(RowDate) == 3 ? "Mar" : 
  MONTH(RowDate) == 4 ? "Apr" : MONTH(RowDate) == 5 ? "May" : MONTH(RowDate) == 6 ? "Jun" : 
  MONTH(RowDate) == 7 ? "Jul" : MONTH(RowDate) == 8 ? "Aug" : MONTH(RowDate) == 9 ? "Sep" : 
  MONTH(RowDate) == 10 ? "Oct" : MONTH(RowDate) == 11 ? "Nov" : MONTH(RowDate) == 12 ? "Dec" : 
  "ERR") + " (" + (DT_WSTR,4)YEAR(RowDate) + ")"

yyyy-mm-dd

The common yyyy-mm-dd format is often used in file names, for example:
 C:\Temp\ErrorCodes\2005-11-18.txt
A sample expression to achieve this is:
 "C:\\Temp\\ErrorCodes\\" + (DT_WSTR,4)YEAR(GETDATE()) + "-" 
    + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" 
    + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + ".txt"
A similar expression, but this time deriving the file name based on yesterday’s date, useful for loading the previous day's data:
 "C:\\Temp\\ErrorCodes\\" + (DT_WSTR,4)YEAR(DATEADD("dd", -1, GETDATE())) + "-" 
    + RIGHT("0" + (DT_WSTR,2)MONTH(DATEADD("dd", -1, GETDATE())), 2) + "-" 
    + RIGHT("0" + (DT_WSTR,2)DAY(DATEADD("dd", -1, GETDATE())), 2) + ".txt"

yyyy-mm-dd hh:nn:ss

Another simple time and date expression example:
 2006-06-22 11:48:52
 (DT_WSTR,4)YEAR(GETDATE()) + "-" 
    + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" 
    + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " "
    + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":"
    + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":"
    + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)
Or alternatively:
 (DT_WSTR, 10) (DT_DBDATE) GETDATE()  + " " + (DT_WSTR, 8) (DT_DBTIME) GETDATE()

dd-mm-yyyy

 RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + "-"
    + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" 
    + (DT_WSTR,4)YEAR(GETDATE())
 18-07-2006

yyyymmdd

A simple yyyymmdd formatted string from a DateTime type variable
 (DT_WSTR,4)YEAR(@[User::DateTimeVar])
    + RIGHT("0" + (DT_WSTR,2)MONTH(@[User::DateTimeVar]), 2)
    + RIGHT("0" + (DT_WSTR,2)DAY(@[User::DateTimeVar]), 2)
An alternative yyyymmdd formatted string from a DateTime type variable.
 (DT_WSTR,8) (
   (YEAR(@[User::DateTimeVar]) * 10000) + 
    (MONTH(@[User::DateTimeVar]) * 100) + 
    DAY(@[User::DateTimeVar])
    )

yyyymmdd hh:nn:ss.mi

 
 (DT_WSTR,8) (
    (YEAR(@[User::MaxStartDate]) * 10000) + 
      (MONTH(@[User::MaxStartDate]) * 100) + 
      DAY(@[User::MaxStartDate]) 
    ) + " " + 
    RIGHT("0" + (DT_WSTR,2)DATEPART("hh", @[User::MaxStartDate]), 2) + ":"
 + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", @[User::MaxStartDate]), 2) + ":"
 + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", @[User::MaxStartDate]), 2) + "."
 + (DT_WSTR,3)DATEPART("Ms", @[User::MaxStartDate])
 20070511 09:40:38.123

ISDATE() workaround for date values

This checks against a string value where the source system used "00/00/00" as a lack of date. There were also columns that were out of the normal range for date values (AD 1, 0600, etc). This expression NULLs those values out. I figured that someone may have been struggling with this and the lack of an ISDATE function for expressions. It could be easily adapted to handle other date formats and checking for out of range dates.
 (Date_To_Check == "00/00/00" || (DT_Date)Date_To_Check < (DT_DATE)"1753-1-1") ? NULL(DT_DATE) : (DT_Date)Date_To_Check 

Get Date - Remove Time

If you wish to return the date only, so setting the time to 00:00 you can easily do this by casting to DT_DBDATE. The data type has limited support, so casting it back to a DT_DATE will allow you to use it more readily.
 (DT_DATE)(DT_DBDATE)@[User::WorkingDate]
Or, alternatively:
 DATEADD("day",DATEDIFF("day",(DT_DBTIMESTAMP)0,GETDATE()),(DT_DBTIMESTAMP)0)

Calculate the Beginning of a Previous Month

This expression starts from today, moves back three months (as an example), subtracts the day-count from the current day-of-month to get the first day, then converts the expression to a DT_DBDATE type (which does not support a time component) then converts it back to a regular DT_DATE, which does have a time component - but now it's truncated the time to 00:00 AM.
 (DT_DATE)(DT_DBDATE)DATEADD("dd",-1 * (DAY(GETDATE())-1),DATEADD("month",-3,GETDATE()))

Calculate the End of a Previous Month

To get Midnight on the last day of the previous month, we back up to the first day of the immediately following month, truncate the time to 00:00 (as in the previous example) and then subtract 1 minute to get the ending time of the previous day. (Note, in SQL Server 2005 SP2, subtracting 3ms to get the absolute last time-slice of the previous day did not work properly with the MONTH() function.)
 DATEADD("mi",-1,(DT_DATE)(DT_DBDATE) DATEADD("dd",0,DATEADD("dd",-1 * (DAY(GETDATE())-1),DATEADD("month",-2,GETDATE()))))

Getting the Fiscal Year for a Date

To get the fiscal year for a given date, use the conditional operator to check the month part of the date, and return either the year part of the date, or the year part of the date plus one depending on the cutoff of the fiscal year definition. This sample assumes a fiscal year that ends June 30th:
 MONTH( @[User::InputDate]  ) <= 6 ? YEAR ( @[User::InputDate]  )  : YEAR ( @[User::InputDate]  )  + 1

The Execute SQL Task


In this article we are going to take you through the Execute SQL Task in SQL Server Integration Services for SQL Server 2005 (although it appies just as well to SQL Server 2008).  We will be covering all the essentials that you will need to know to effectively use this task and make it as flexible as possible. The things we will be looking at are as follows:
  • A tour of the Task.
  • The properties of the Task.
After looking at these introductory topics we will then get into some examples. The examples will show different types of usage for the task:
  • Returning a single value from a SQL query with two input parameters.
  • Returning a rowset from a SQL query.
  • Executing a stored procedure and retrieveing a rowset, a return value, an output parameter value and passing in an input parameter.
  • Passing in the SQL Statement from a variable.
  • Passing in the SQL Statement from a file.

Tour Of The Task

Before we can start to use the Execute SQL Task in our packages we are going to need to locate it in the toolbox. Let's do that now. Whilst in the Control Flow section of the package expand your toolbox and locate the Execute SQL Task. Below is how we found ours.
Find
Now drag the task onto the designer. As you can see from the following image we have a validation error appear telling us that no connection manager has been assigned to the task. This can be easily remedied by creating a connection manager. There are certain types of connection manager that are compatable with this task so we cannot just create any connection manager and these are detailed in a few graphics time.
Drop
Double click on the task itself to take a look at the custom user interface provided to us for this task. The task will open on the general tab as shown below. Take a bit of time to have a look around here as throughout this article we will be revisting this page many times.
General
Whilst on the general tab, drop down the combobox next to the ConnectionType property. In here you will see the types of connection manager which this task will accept.
ConnectionTypes
As with SQL Server 2000 DTS, SSIS allows you to output values from this task in a number of formats. Have a look at the combobox next to the Resultset property. The major difference here is the ability to output into XML.
ResultsetTypes
If you drop down the combobox next to the SQLSourceType property you will see the ways in which you can pass a SQL Statement into the task itself. We will have examples of each of these later on but certainly when we saw these for the first time we were very excited.
SourceType
Next to the SQLStatement property if you click in the empty box next to it you will see ellipses appear. Click on them and you will see the very basic query editor that becomes available to you.
QueryEditor
Alternatively after you have specified a connection manager for the task you can click on the Build Query button to bring up a completely different query editor. This is slightly inconsistent.
AlternateEditor
Once you've finished looking around the general tab, move on to the next tab which is the parameter mapping tab. We shall, again, be visiting this tab throughout the article but to give you an initial heads up this is where you define the input, output and return values from your task. Note this is not where you specify the resultset.
ParamBlank
If however you now move on to the ResultSet tab this is where you define what variable will receive the output from your SQL Statement in whatever form that is.
ResultsetBlank
Property Expressions are one of the most amazing things to happen in SSIS and they will not be covered here as they deserve a whole article to themselves. Watch out for this as their usefulness will astound you.
ExpressionsTabBlank
For a more detailed discussion of what should be the parameter markers in the SQL Statements on the General tab and how to map them to variables on the Parameter Mapping tab see Working with Parameters and Return Codes in the Execute SQL Task.

Task Properties

There are two places where you can specify the properties for your task. One is in the task UI itself and the other is in the property pane which will appear if you right click on your task and select Properties from the context menu. We will be doing plenty of property setting in the UI later so let's take a moment to have a look at the property pane. Below is a graphic showing our properties pane.
PropertiesPane
Now we shall take you through all the properties and tell you exactly what they mean. A lot of these properties you will see across all tasks as well as the package because of everything's base structure The Container.
BypassPrepare
Should the statement be prepared before sending to the connection manager destination (True/False)
Connection
This is simply the name of the connection manager that the task will use. We can get this from the connection manager tray at the bottom of the package.
DelayValidation
Really interesting property and it tells the task to not validate until it actually executes. A usage for this may be that you are operating on table yet to be created but at runtime you know the table will be there.
Description
Very simply the description of your Task.
Disable
Should the task be enabled or not? You can also set this through a context menu by right clicking on the task itself.
DisableEventHandlers
As a result of events that happen in the task, should the event handlers for the container fire?
ExecValueVariable
The variable assigned here will get or set the execution value of the task.
Expressions
Expressions as we mentioned earlier are a really powerful tool in SSIS and this graphic below shows us a small peek of what you can do. We select a property on the left and assign an expression to the value of that property on the right causing the value to be dynamically changed at runtime.
PropertyExpressions
One of the most obvious uses of this is that the property value can be built dynamically from within the package allowing you a great deal of flexibility
FailPackageOnFailure
If this task fails does the package?
FailParentOnFailure
If this task fails does the parent container? A task can he hosted inside another container i.e. the For Each Loop Container and this would then be the parent.
ForcedExecutionValue
This property allows you to hard code an execution value for the task.
ForcedExecutionValueType
What is the datatype of the ForcedExecutionValue?
ForceExecutionResult
Force the task to return a certain execution result. This could then be used by the workflow constraints. Possible values are None, Success, Failure and Completion.
ForceExecutionValue
Should we force the execution result?
IsolationLevel
This is the transaction isolation level of the task.
IsStoredProcedure
Certain optimisations are made by the task if it knows that the query is a Stored Procedure invocation. The docs say this will always be false unless the connection is an ADO connection.
LocaleID
Gets or sets the LocaleID of the container.
LoggingMode
Should we log for this container and what settings should we use? The value choices are UseParentSetting, Enabled and Disabled.
MaximumErrorCount
How many times can the task fail before we call it a day?
Name
Very simply the name of the task.
ResultSetType
How do you want the results of your query returned? The choices are ResultSetType_None, ResultSetType_SingleRow, ResultSetType_Rowset and ResultSetType_XML.
SqlStatementSource
Your Query/SQL Statement.
SqlStatementSourceType
The method of specifying the query. Your choices here are DirectInput, FileConnection and Variables
TimeOut
How long should the task wait to receive results?
TransactionOption
How should the task handle being asked to join a transaction?

Usage Examples

As we move through the examples we will only cover in them what we think you must know and what we think you should see. This means that some of the more elementary steps like setting up variables will be covered in the early examples but skipped and simply referred to in later ones. All these examples used the AventureWorks database that comes with SQL Server 2005.

Returning a Single Value, Passing in Two Input Parameters

So the first thing we are going to do is add some variables to our package. The graphic below shows us those variables having been defined. Here the CountOfEmployees variable will be used as the output from the query and EndDate and StartDate will be used as input parameters. As you can see all these variables have been scoped to the package. Scoping allows us to have domains for variables. Each container has a scope and remember a package is a container as well. Variable values of the parent container can be seen in child containers but cannot be passed back up to the parent from a child.
Example1ParametersSet
Our following graphic has had a number of changes made. The first of those changes is that we have created and assigned an OLEDB connection manager to this Task ExecuteSQL Task Connection. The next thing is we have made sure that the SQLSourceType property is set to Direct Input as we will be writing in our statement ourselves. We have also specified that only a single row will be returned from this query. The expressions we typed in was:
SELECT COUNT(*) AS CountOfEmployees FROM HumanResources.Employee WHERE (HireDate BETWEEN ? AND ?)

Example1ShowStatement
Moving on now to the Parameter Mapping tab this is where we are going to tell the task about our input paramaters. We Add them to the window specifying their direction and datatype. A quick word here about the structure of the variable name. As you can see SSIS has preceeded the variable with the word user. This is a default namespace for variables but you can create your own. When defining your variables if you look at the variables window title bar you will see some icons. If you hover over the last one on the right you will see it says "Choose Variable Columns". If you click the button you will see a list of checkbox options and one of them is namespace. after checking this you will see now where you can define your own namespace.
Example1ParamMap
The next tab, result set, is where we need to get back the value(s) returned from our statement and assign to a variable which in our case is CountOfEmployees so we can use it later perhaps. Because we are only returning a single value then if you remember from earlier we are allowed to assign a name to the resultset but it must be the name of the column (or alias) from the query.
Example1ResultSet
A really cool feature of Business Intelligence Studio being hosted by Visual Studio is that we get breakpoint support for free. In our package we set a Breakpoint so we can break the package and have a look in a watch window at the variable values as they appear to our task and what the variable value of our resultset is after the task has done the assignment. Here's that window now.
Example1WatchWindow
As you can see the count of employess that matched the data range was 2.

Returning a Rowset

In this example we are going to return a resultset back to a variable after the task has executed not just a single row single value. There are no input parameters required so the variables window is nice and straight forward. One variable of type object.
VariablesExample2
Here is the statement that will form the soure for our Resultset.
select  
p.ProductNumber, p.name, pc.Name as ProductCategoryName
FROM Production.ProductCategory pc
JOIN Production.ProductSubCategory psc
ON pc.ProductCategoryID = psc.ProductCategoryID
JOIN Production.Product p
ON psc.ProductSubCategoryID = p.ProductSubCategoryID
We need to make sure that we have selected Full result set as the ResultSet as shown below on the task's General tab.
Example2ResultsetOnGeneralTab
Because there are no input parameters we can skip the parameter mapping tab and move straight to the Result Set tab. Here we need to Add our variable defined earlier and map it to the result name of 0 (remember we covered this earlier)
Example2ResultsetMap
Once we run the task we can again set a breakpoint and have a look at the values coming back from the task. In the following graphic you can see the result set returned to us as a COM object. We can do some pretty interesting things with this COM object and in later articles that is exactly what we shall be doing.
Example2WatchWindow

Return Values, Input/Output Parameters and Returning a Rowset from a Stored Procedure

This example is pretty much going to give us a taste of everything. We have already covered in the previous example how to specify the ResultSet to be a Full result set so we will not cover it again here. For this example we are going to need 4 variables. One for the return value, one for the input parameter, one for the output parameter and one for the result set. Here is the statement we want to execute. Note how much cleaner it is than if you wanted to do it using the current version of DTS.
Example3ShowStatement
In the Parameter Mapping tab we are going to Add our variables and specify their direction and datatypes.
Example3ParamMap
In the Result Set tab we can now map our final variable to the rowset returned from the stored procedure.
Example3ResultSet
It really is as simple as that and we were amazed at how much easier it is than in DTS 2000.

Passing in the SQL Statement from a Variable

SSIS as we have mentioned is hugely more flexible than its predecessor and one of the things you will notice when moving around the tasks and the adapters is that a lot of them accept a variable as an input for something they need. The ExecuteSQL task is no different. It will allow us to pass in a string variable as the SQL Statement. This variable value could have been set earlier on from inside the package or it could have been populated from outside using a configuration. The ResultSet property is set to single row and we'll show you why in a second when we look at the variables. Note also the SQLSourceType property. Here's the General Tab again.
Example5ShowStatement
Looking at the variable we have in this package you can see we have only two. One for the return value from the statement and one which is obviously for the statement itself.
Example5ParametersSet
Again we need to map the Result name to our variable and this can be a named Result Name (The column name or alias returned by the query) and not 0.
Example5ResultSet
The expected result into our variable should be the amount of rows in the Person.Contact table and if we look in the watch window we see that it is.
Example5WatchWindow

Passing in the SQL Statement from a File

The final example we are going to show is a really interesting one. We are going to pass in the SQL statement to the task by using a file connection manager. The file itself contains the statement to run. The first thing we are going to need to do is create our file connection mananger to point to our file. Click in the connections tray at the bottom of the designer, right click and choose "New File Connection"
Example6FileConnection
As you can see in the graphic below we have chosen to use an existing file and have passed in the name as well. Have a look around at the other "Usage Type" values available whilst you are here.
Example6FileSetup
Having set that up we can now see in the connection manager tray our file connection manager sitting alongside our OLE-DB connection we have been using for the rest of these examples.
Example6ConnectionsTray
Now we can go back to the familiar General Tab to set up how the task will accept our file connection as the source.
Example6ShowStatement
All the other properties in this task are set up exactly as we have been doing for other examples depending on the options chosen so we will not cover them again here.

We hope you will agree that the Execute SQL Task has changed considerably in this release from its DTS predecessor. It has a lot of options available but once you have configured it a few times you get to learn what needs to go where. We hope you have found this article useful.