Friday, June 27, 2008

Looking for a Date - What's in a Name?

I've blogged about using SSIS to create text files with dynamic file names before, but there's another scenario that keeps coming up time and again. It looks something like this:

"I need to export data from a database into a text file. I have this working, but I need the text file to have a name that's based on the current date, like MyOutputFilePrefix_YYYY-MM-DD-HH-MM-SS.txt. How do I do this?"

It should come as no surprise that the short answer is "use expressions." Expressions are (in my humble opinion, of course) the single most powerful feature in the SSIS developer's toolbox, and are the primary mechanism for adding dynamic functionality to SSIS packages.

Bur of course "use expressions" doesn't give you all the information you need, so here is a quick walkthrough that shows all of the steps involved.

  1. Start off by creating or locating a flat file that has the format that you need. This will give you a head-start for configuring your Flat File Connection Manager later on. Since I'm working on a simple demo, my text file is appropriately simple:

    01
  2. Next, add a Flat File Connection Manager to your SSIS package, and update its properties to reference the sample flat file you created above:

    02
  3. Make sure that the columns you defined in the file are being parsed correctly:

    03
  4. And update the properties (generally the data type) of the columns as needed. In this scenario, we're setting the data type of the ID column to be a four-byte signed integer:

    04
  5. Next, add an OLE DB Connection Manager (or whatever makes sense for your source database) to your package, configure it as necessary[1], and add a Data Flow task to the package as well:

    05
  6. Inside the Data Flow task, add an OLE DB Source component (or whatever makes sense for your source database) and configure it with your source query:

    06
  7. Next, add a Flat File Destination component to the data flow and connect it to the source component:

    07
  8. Configure the Flat File Destination to use the Flat File Connection Manager and ensure that its column mappings are configured correctly:

    08a
    08b
  9. Run the package to make sure that it works:

    09
  10. And test it by checking the contents of the target text file:

    10
  11. And now we're ready to start. That's right, the last 10 steps were included to show how I got to the starting point for adding the dynamic functionality that is the whole point of the post. What we've done above is set up a simple package and data flow that exports data to a text file, which is (I assume) where the people who keep asking the question at the top of the post are getting stuck. And since we walked through it step-by-step together, everyone can see that there is no prestidigitation involved.
    So let's start off by creating three different package variables, Foldername, FileName and FilePath:

    11
  12. Set the value property of the FolderName variable to the path of the folder where you want your files to be created:

    12
  13. Set the EvaluateAsExpression property of the FileName variable to True and set the Expression property to this expression:
  14. "MyOutputFilePrefix_" + (DT_WSTR,4)YEAR(@[System::StartTime]) + "-"
        + RIGHT("0" + (DT_WSTR,2)MONTH(@[System::StartTime]), 2) + "-"
        + RIGHT("0" + (DT_WSTR,2)DAY( @[System::StartTime]), 2) + "-"
        + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", @[System::StartTime]), 2) + "-"
        + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", @[System::StartTime]), 2) + "-"
        + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", @[System::StartTime]), 2) + ".txt"

    This will evaluate to a filename like MyOutputFilePrefix_YYYY-MM-DD-HH-MM-SS.txt, as requested above. [2]

    13a

    13b 

  15. Set the EvaluateAsExpression property of the FilePath variable to True and set the Expression property to this expression:

    @[User::FolderName] +  @[User::FileName]

    14 
  16. At this point we have a variable, FilePath, that will always evaluate to a fully qualified file path that is dynamically updated to reflect the time the package started executing. This is exactly what we need, right? So the one thing that remains to be done is to use this value to create the files being exported by the data flow. And to do this we just need to update the Flat File Connection Manager to base its ConnectionString property on this expression:

    @[User::FilePath]

    15a
    15b
  17. Then, run the package a few times, and take a look in the output folder:

    16 

Pretty simple, eh? Once we had the base package (the starting point for the whole exercise) set up, it was simply a matter of setting a few property expressions to make the whole thing work as needed.

It's also worth noting that the technique where there are three variables to contain the file path is completely optional as well - you could just as easily build a single (although admittedly more complex) expression for the ConnectionString property, and skip the variables entirely. I personally prefer having the variables to contain the intermediate values that go into the file path because in most situations there are opportunities for reuse of these intermediate values, and having them stored in variables make that reuse very simple.

And of course, you can easily update the FileName expression as needed to get the file name you require. The SQLIS.com wiki has a page dedicated to date expressions, and I will generally start there whenever I need to write a date expression myself. In fact, you'll probably notice that the expression I used for the FileName variable was blatantly stolen (and then modified just a little) from one of the examples on the SQLIS wiki site.

So once again we've witnessed the power of expressions in SSIS. By setting just a few properties to evaluate as expressions, we've quickly and easily added dynamic functionality to a package. What could be better?

 

[1] Since the purpose of this post is to focus on the dynamic file name, I'm being deliberately vague here. This is stuff that you should know already, so if you don't, check here: New to SSIS- Start Here!

[2] Although this example is using the @[System::StartTime] variable, you can use any date variable (or function, like GETDATE) for your expressions - use the one that makes the most sense for you.

Wednesday, June 25, 2008

BIDS Helper and SSIS Deployment

Back in November I posted about the 1.2 release of the amazing BIDS Helper project on CodePlex and the new SSIS-related features it included. Well, the folks who contribute to the BIDS Helper project have been hard at work getting ready for their 1.3 release, and today they checked into TFS the first set of features designed to provide real-world deployment capabilities from within the Visual Studio (BIDS) development environment.

Now, not only can you create the standard deployment manifest[1] you can also deploy automatically and (here's the exciting part!) have BIDS Helper automatically create a batch file that calls DTUTIL each time you build your project.

How cool is that!

The reason I'm so excited about low-tech batch files is that they are incredibly simple to integrate into any deployment process, and they're completely hands-free. They may not be sexy, but they're close to perfect nonetheless.

Take a look here for more information: http://www.codeplex.com/bidshelper/Wiki/View.aspx?title=Deploy SSIS Packages

The bad news is that version 1.3 is not yet ready for release, so if you want to start taking advantage of this functionality you will need to download the BIDS Helper source code and compile it yourself. Which I am now about to do...

[1] Which seems like a good start, but quickly becomes a dead-end, because it is dependent on a user clicking and typing every time it is used, which makes it very undesirable in a real-world deployment scenario.

SSIS and SQL Server Agent - Choosing the Right Job Step Type

My "SSIS and SQL Server Agent" post is the most frequently accessed post on my blog, or at least it has been for the two months that I've actually been tracking site usage. But some recent posts on the SSIS Forums on MSDN have made me realize that it was probably long overdue for a follow-up focused choosing the correct job step type.

Microsoft has provided two different SQL Server Agent job step  types that you can use to execute SQL Server Integration Services Packages:

  1. The "SQL Server Integration Services Package" job step type
  2. The "Operating system (CmdExec)" job step type.

Now which one leaps out at you as being ideal for running SQL Server Integration Services packages?

Unfortunately, despite the name and the oh-so-friendly GUI through which you can specify all sorts of options, the SQL Server Integration Services Package job step type is not the one you want to use. There are quite a few reasons I believe this (and it's worth pointing out that while there are people who agree with me, there are some very talented SSIS people out there who do not) including:

  • Consistency: You can create a batch file that calls DTEXEC, test that execution outside of SQL Server Agent, and then copy and paste the DTEXEC command line into the SQL Server Agent job. This minimizes the number of environmental variables[1] that change between testing package execution outside of SQL Server Agent and testing package execution within a SQL Server Agent job.
  • Discoverability: I realize that this won't apply to everyone, but I personally find it much simpler to look at command line switches and options than to look at nine different tabs in a tabbed window. Looking at the command line I know that I'm seeing everything. Looking through the tabs, I'm pretty sure I'm going to miss something.
  • Troubleshooting and Error Output: This is the big one. When you run a package through the SQL Server Integration Services Package job step type, you're limited to the error logging that is already configured within the package itself, and this isn't always sufficient to diagnose and resolve problems with the job. But when you execute a package through DTEXEX and the the CmdExec job step type, you have more options that make tracking down and resolving problems much simpler.

So how do you do it? And do you really want to, if you're not one of those weird people who would rather have a command line than a GUI?

Well, the answer to the second question here is yes. Yes you do. Because even though you're using the CmdExec job step type, you still have a GUI to use. And here's how.

  1. Double-click on the package you want to run.[2] This will open up DTEXECUI, the Execute Package Utility.
  2. In DTEXECUI, specify all of the options that you need by using its nice friendly GUI.
  3. On the Command Line tab in DTEXECUI, highlight and copy the Command line text - these are the switches and options that need to be specified for DTEXEC to duplicate the options you selected in the GUI:

    Use DTEXECUI to build your command line
  4. In you SQL Server Agent job, add a new job step, and specify the job step type as CmdExec. In the Command text box, type DTEXEC and a space, and then paste the command line text that you copied from DTEXECUI earlier[3]:

    Paste the command line text into your job step
  5. On the advanced tab of the New Job Step dialog box, enter a file path and name in the Output File text box. (This is the big thing.) With this specified, the output from DTEXEC, which is exactly what you want when troubleshooting problems, will be written to a text file. You can also specify whether the file should be overwritten or appended to with each execution.

    Specify an output file for the job step

Now, when you execute your SQL Server Agent job, all DTEXEC output will be written to this text file. And if something goes wrong, you now have a single, easy to use location for tracking down and resolving the problems.

One of the most common things that the MVPs and other people who help out on the SSIS forums request is "the complete set of error messages and warnings from the package execution."[4] The reason we ask for this is that it's pretty much impossible to remotely troubleshoot someone else's problems without complete and explicit output. And the greatest thing about using the CmdExec job step type is that all of this information is now in one place. Copy and paste the errors and warnings, and help is (hopefully) on your way.

 

[1] Not Windows environment variables - I'm talking here about "things that are important to your deployment environment."

[2] If your package is stored in SQL Server and not on the file system, you can still use this basic technique, but you will have to browse to and select the package from within DTEXECUI, as opposed to double-clicking on the package on the file system.

[3] You can also specify the fully qualified path to DTEXEC.EXE - this is helpful if DTEXEC is not on the path, or if you're on a 64-bit server and want to explicitly select the 32- or 64-bit version of DTEXEC for this package.

[4] And we're not the only ones who ask for this. Your in-house support folks will probably ask for the same thing if you have a support team who works with SSIS.

Monday, June 23, 2008

File Name Expressions

A recent post on the SSIS Forums on MSDN reminded me how anti-intuitive it can sometimes be to work with SSIS expressions. For example, it's quite common (such as when using the File enumerator for the Foreach Loop container) to have a package variable that contains the fully-qualified file name of a file. But what if you need only a portion of the file name?

Well, the obvious answer (as I mentioned in an earlier post on expressions) is to look at the SQLIS.com Wiki for expression examples, because there are some good examples up there, including these first two. So here are a few more, each of which includes sample output for this sample input:

C:\Projects2008\RC0_SSIS_Test\RC0_SSIS_Test\FileExpressions.dtsx

Get the filename from a full file path:

RIGHT( @[User::FileName], FINDSTRING( REVERSE( @[User::FileName] ), "\\", 1 ) - 1 )

Output: FileExpressions.dtsx

Get the directory from a full file path:

SUBSTRING( @[User::FileName], 1, LEN( @[User::FileName] ) - FINDSTRING( REVERSE( @[User::FileName] ), "\\", 1 ) )

Output: C:\Projects2008\RC0_SSIS_Test\RC0_SSIS_Test

But what if your needs are covered there? Well, here are a few more examples:

Get the file extension from a full file path or file name:

RIGHT( @[User::FileName], FINDSTRING( REVERSE( @[User::FileName] ), ".", 1 ) - 1 )

Output: dtsx

Get the file name minus the extension from a full file path:

SUBSTRING (@[User::FileName], LEN( @[User::FileName] ) - FINDSTRING( REVERSE( @[User::FileName] ), "\\", 1) + 2,  LEN (RIGHT( @[User::FileName], FINDSTRING( REVERSE( @[User::FileName] ), "\\", 1 ) - 1 ) ) - FINDSTRING( REVERSE( @[User::FileName] ), ".", 1 )  )

Output: FileExpressions

Expressions are probably the single most powerful tool in the SSIS developer's toolset, so the more you use them the more you're likely to love them. But sometimes having a few good examples is the best way to get over the initial learning curve.

Friday, June 20, 2008

BI for the Virtual Guy

Yeah, I know I'm stretching for the title of this post, but my allergies are killing me today and this is really the best I can do at the moment.

So what's this "Virtual" bit all about. It's about the first-ever SSWUG Virtual Business Intelligence Conference, coming this September to a computer near you. I'm in the process of helping to organize the conference and I've been having a blast. We have quite a few great BI speakers lined up and are in the process of finalizing the lists of speakers and sessions.[1]

But why do I mention this today?

SSWUG is about to kick off its second SQL Server Virtual Conference next week - it's being held from June 24 to June 26. And I'm excited that I get to attend. The reason I'm excited about attending is the very cool format of the conference - check this out:

http://www.vconferenceonline.com/sswug/demo.asp

The virtual conference format pulls together the best of "real" in-person conferences, along with the best of an online learning experience. The video on the page above shows footage from the first SQL Server Virtual Conference[2] and although the video has catchier music than you're likely to get during the actual sessions, it gives you a great taste of what the virtual conference format has to offer, such as :

  • High-definition video
  • High-quality audio
  • Real-life views of the speaker, the slides and the demos
  • Everything delivered online - no need to leave your desk

And there are some things that don't come through in the sample video, but you also get:

  • Interactive online chats and Q&A with the speakers
  • Downloadable PowerPoint slide decks
  • Downloadable demo files

But what is most exciting to me is that on top of all of these things, the virtual conference is flexible. The conference is three days long, and there are three sessions going on at any given time. At a traditional conference you would need to decide which session to attend, and the other two would be unavailable. Here, each day's content is repeated three times throughout the day, so if you don't catch a session the first time around, you can go back and view it later, so you have the flexibility you normally only get with online content and the interactivity (remember the Q&A with the speakers?) that you normally only get with an in-person conference. And to make things even better, if none of the primary times work for you (or if you get called into emergency meetings, as is often the case in IT) you also have the option to view any of the conference sessions on demand for the two weeks following the conference.

When I was first contacted about participating in the Virtual Business Intelligence Conference, I was more than a little skeptical. I pictured something like a ReadyTalk or Go To Meeting, with poor quality audio and video, and few options for interacting with the speakers and with other attendees. Instead, I found a platform that really seems to bring together the best of the physical and virtual formats, and I was delighted to get involved.

If this sounds interesting to you too, please stay tuned. I'll post more information over the weeks ahead, as we move closer to the conference dates from September 24 to September 26. So if you have any questions, please let me know, and please spread the word as well. There are a lot of people out there who can benefit from this content, and not everyone can make the trip to Orlando for TechEd or to Seattle for the Microsoft BI conference, so please help let them know that there is another option out there.

UPDATE 24 June, 2008:

It always weirds me out when I learn that people actually read my blog. I get enough information from Google Analytics to know that I get a decent number of hits each day, but that's not the same as getting an email from a real person about a post.

Like the email that I got today.

This morning I received an email from the account manager responsible for the conferencing solution that I use for work, wanting to know how she could work with me to resolve those problems. (How's that for great customer service? ;-) Reading back through this post I can see how it could be interpreted as "these conferencing systems are bad" as opposed to the "these conferencing systems are not ideal for the virtual conference format" message that I had intended. Here is the relevant part of my response to her, hopefully to eliminate the negativity that slipped into the post.

I didn’t mean to imply that I had any issues with ReadyTalk, LiveMeeting or GoTo Meeting for their stated purposes; simply that I don’t believe that they are ideal for the virtual conference format. The issues that I see are:

· Attendee join/leave – Most conferencing systems will announce each attendee by name and/or with a beep when the attendee joins or leaves the conference. For a conference call this functionality makes sense, but for a virtual conference this would be very disruptive.
· Audio Quality – The quality of the presenter audio in a conference call is dependent on the quality of the presenter’s phone line and the background noise in the presenter’s location, usually a home or office. Obviously this isn’t a problem with the conferencing system, but for a virtual conference it would negatively impact the attendee experience when compared to audio recorded with a professional microphone in a studio and then tweaked as needed before broadcast.
· Time-bound interaction – In a conference call, the only time that attendees can chat is during the session itself, and because the presenter is running the slides and/or demos, the attendees are limited to asking questions to (and getting answers from) helpers other than the presenter. Although the video may be recorded and made available for on-demand viewing, this is a unidirectional viewing; there are no options available for participants to interact. Again, this makes sense for a conference call, but for a virtual conference, it would be ideal to have the core presentation (slides, demos and presenter) and the attendee interaction/chat available independently, enabling the speaker to answer questions while the recorded session is being viewed.

I hope this helps clear up any confusion I may have caused!

[1] I know that quite a few strong BI speakers read this blog - if you're interested in being considered as a speaker, feel free to post a comment or send me an email over the next few days.

[2] Which was a huge success, which is why SSWUG is organizing another one and branching out to cover BI, SharePoint and .NET as well.

Splitting a Delimited Column in SSIS

A recent post on the MSDN SSIS Forums has reminded me that I've been meaning to post on this technique for quite a few months now. The basic problem looks like this: The input rows in a data flow contain a key field and a "list field" whose contents are made up of a delimited list of values. Like this:

KeyField    ListField
1           a,b,c
2           b,c
3           b,d,e
4           c,f,h
5           a,b
  

And the output needs to look like this:

KeyField   ListItem
1          a
1          b   
1          c
2          b       
2          c
3          b
3          d
3          e
4          c
4          f
4          h
5          a
5          b

The bad news is that there isn't any magical "Split Transformation" in SSIS. There are enough variations on data types and delimiters that it would probably be difficult to implement this as a transformation component. The good news is that it is trivial to implement this as a Script Component within the package. Here's how:

  1. Start by adding a data flow task to your package, and adding an OLE DB Source component (that returns the input data above) to the data flow. Then add a Script Component to the data flow as well.
  2. When prompted to select the type of component you want to create with the Script Component, select Transformation - it's the default, so this should be super easy.

    01-SelectType
  3. Next, connect the data flow path arrow from the Source component to the new Script transformation. Because the SSIS data flow is so heavily dependent on metadata, we can't really do anything meaningful with the Script Component until it knows what input data it will receive.

    02-HookUpPath
  4. Next, right-click on the Script Component and select Edit. In the Script Transformation Editor dialog box, select both columns to make them available as input columns so they are available in the Script code.

    03-Inputs
  5. Next comes the one "tricky" part: marking the transformation as asynchronous. Because the transformation will be producing more output rows than it receives input rows, this is a vital step that is sometimes missed by inexperienced SSIS developers. Mark the transformation as asynchronous by setting the SynchronousInputID property of the output to None.

    04-MakeAsynch
  6. Now, because we are building our own output buffer (one of the characteristics of an asynchronous data flow component) we need to add the columns that the output buffer will contain. Select the transformation's output, click Add Column and set the properties (mainly the name and data type) appropriately.

    05-BuildOutput
  7. Finally, what we've all been waiting for: the code. Click on the Design Script button and add the code to perform the actual split.

    06-DesignScript

  8. Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

        Dim keyField As Integer = Row.KeyField
        Dim itemList As String = Row.ListField
        Dim delimiter As String = ","

        If Not (String.IsNullOrEmpty(itemList)) Then

            Dim inputListArray() As String = _
                itemList.Split(New String() {delimiter}, _
                StringSplitOptions.RemoveEmptyEntries)

            For Each item As String In inputListArray
                With Output0Buffer
                    .AddRow()
                    .KeyField = keyField
                    .ListItem = item
                End With
            Next

        End If

    End Sub

  9. Once the code is in place, the last thing we need to do is to add a Row Sampling transformation (this one is handy because if it has no output data paths, it doesn't really do anything, and it doesn't require any configuration) and connect the output from the Script Component to it, with a Data Viewer attached. This will let us easily examine the output records from the script.

    07-FinalDataFlow
  10. Now, when you execute the package, you can see the split output data as desired.

    08-DataViewerOutput

Well, that ended up having more steps (and more pretty pictures) than I expected it to, but I stand by my initial assessment of this as being a trivial task, once you've seen how the Script Transformation works. And if this still seems complicated to you, make sure you check out The Rational Guide to Extending SSIS 2005 with Script by Donald Farmer. It's an excellent book that anyone who expects to spend time writing script in SSIS should read.

Thursday, June 19, 2008

New SSIS Project Templates in RC0

I've finally found the time to install SQL Server 2008 RC0 (although my SSIS/BIDS install is corrupted so I have not been able to run SSIS in RC0 through its paces) and noticed something interesting. I was creating a new C# project and noticed this:

NewProjectTemplates

Do you notice the two new project templates in the tree view on the left? That's right - Microsoft has added new class library (DLL) templates for creating custom Control Flow tasks and Data Flow components in C# and VB.NET. It's pretty unlikely that SSIS component development will ever approach the ease of use of the Script Task and Script Component, but having a Visual Studio project template that sets up much of the component plumbing is a nice step forward.

UPDATE: Upon further reflection (and a very helpful email) it turns out that these project templates are not designed for SSIS component developers. They are instead (as the project names should have clued me in, were I not so excited over my discovery) the templates that are used by Visual Studio Tools for Applications (VSTA) in the Script Task and Script Component inside a package. When you add a new Script Task or Script Component to your package, VSTA creates a new instance of one of these templates.