Using SSIS to Loop Over Result Set and Dynamically Generate Output Files

This post is inspired largely by Ken Simmons’ excellent primer at SQLServerCentral.com. All I’ve done is extend it to a full result set.

Scenario: Let’s suppose one of the more successful sales partners at your organization created a slick spreadsheet in Excel that tracks key performance indicators. After a meeting, the entire department wants their own individual CSV so they can build a spreadsheet that looks exactly like hers. With some quick work in SSIS, it’s possible to deliver a unique CSV for each person.

The sales department wants to tracks orders along with customers, perhaps something like the query below:


We will want only the customers for whom the sales person has an order with to get included in the sales person’s spreadsheet. To start, we will begin as Ken Simmon’s article begins. In your SSIS project, drag an Execute SQL Task from the toolbox into the control flow.


Right click and edit the task. Set the ResultSet to, “Full Result Set”. In the SQL Statement section, make sure your ConnectionType is set to OLE DB and click on new connection.


Build out your connection as you normally would to the AdventureWorks database. Mine looks like the following:


Click the ellipses next to SQLStatement and put in the following query, “SELECT DISTINCT CONVERT(NVARCHAR(4), Sales.BusinessEntityID) AS BusinessEntityID FROM Sales.SalesPerson”:


Next, click the Result Set section in the Execute SQL Task Editor and click the, “Add” button, select, “New Variable, and create a variable as the one below. Set the Result Name to the number zero (0) and give it a variable name. Mine is User::SalesPersonResultSet.


Add another variable. I named mine SalesPersonID and gave it a type of string. Package scope here is important. The scope is set to package so that both the Foreach Loop and the Data Task will be able to use the same variable.


Drag out a Foreach Loop Container onto the Control Flow:


Edit the Foreach Loop Container and click on the, “Collection” section. Set your enumerator to, “Foreach ADO Enumerator”, select the ADO object source variable to be User::SalesPersonResultSet, and the default value of, “Rows in the first table” suffices for this example.


Next, click on Variable Mappings and add the User::SalesPersonID. Here we’re taking each value that is encountered in User:SalesPersonResultSet and setting it to User:SalesPersonID. The Data Task will then operate on SalesPersonID until the Foreach Loop ends.


Drag a Dataflow Task out and drop it into the Foreach Loop Container. Once you’ve done that, click on the Data Flow tab.


Click and drag an OLD DB Source out onto the Data Flow Task and edit it. Your connection manager screen should look like the following:


Click the Parameters button and modify it so it looks like the below:


Click, “Okay” until you’re back to the Data Flow Task tab. Drag out a Flat File Destination, and we’ll build it out much like Ken Simmons did in his article. Create a new Flat File Connection and set it up something like the following:


Next, click on the properties for the Flat File Connections and click on the, “Expressions” ellipses. Set your Property to ConnectionString and build your expression as it shows below:


Once that is done, it’s time to try it out. Click, “OK” until you’re back at the package and click the, “Play” button.


We check the output destination:


And we check the files themselves:


That’s it. I know the post is a little long. There’s lots that can be expanded upon. For example, we can try to change the package to output directly to Excel spreadsheets. I have not done this myself so I don’t know how much of the package must be changed to do so. That might make for a good follow up post. Another thing to do is change the output of the first query to have the sales person’s full name instead of BusinessUnitID, since no one would really find that user friendly. Thanks for reading!

28 Responses to “Using SSIS to Loop Over Result Set and Dynamically Generate Output Files”

  1. August

    Thank you very much for your explication! It has been very useful for me!

    • phouseak

      My pleasure! Please feel free to contact me if you have any questions.

  2. Nasir

    what if salespersonid has character in it how can we handle it.

  3. phouseak

    I think you’re asking if the SalesPersonID has a data type of NVARCHAR? If this is accurate then we won’t need to do anything different. I gave the SalesPersonID a string data type. The SSIS package will just loop over the object types (most likely an array or some related type) until it reaches the end.

  4. Nasir

    great ,it worked fine ,thankyou so much.

  5. phouseak

    That’s great to hear.

  6. Phil

    Thanks for the help, awesome tutorial!

  7. Subrat

    As I am a newBie in SSIS. i was wondering how to create dynamic destinations…..It was great help….Really appreciate ur work……

  8. Adjustable

    Whoa, great submit.Many thanks. Great.

  9. priyaks

    I just happened to see this posting and the logic seems to be nice. I have a question how do I supply multiple parameters and the parameters interchange in the where clause, that is the order of parameters is not the same. I have a project where in there are 10 different criterias for 5 different accounts that need to be plugged in at run time and looped over, these criterias are inputed in the sql where clause and I am thinking of 10 variables for these criterias, but how do I get them in the sql? Any thoughts will be appreciated.

    • phouseak

      Priyaks, I’m uncertain about how one would handle changes in order of parameters. If your where clause is a simple conjunction of parameters (that is something that reads WHERE A AND B AND C), then order would not matter and you can just access the variables in the usual way. Your query in BIDS would look then something like: SELECT X, Y, Z FROM Table WHERE A = @Param1 AND B = @Param2, et cetera. I would recommend reading this link for some insight: http://msdn.microsoft.com/en-us/library/ms140355.aspx

      Good luck! 🙂

  10. Mohamed rafiq

    Phouseak,

    It was really helpful post for me…thanks for the knowledge sharing.
    As i am new to SSIS, i need to know the what exactly does SSIS do in real time in IT industries..How does it work..
    I know my question seems to be silly, But kindly request you to clear my confusion such that i will have a clear vision.
    Kindly mail me at rafiq198925@rediffmail.com.
    Thanks in advance

  11. phouseak

    Mohamed, SSIS can be used for a variety of tasks. It figures prominently with extract, transform, and load operations that are often used as a means of loading data from one database to another. You can read more here: http://en.wikipedia.org/wiki/SQL_Server_Integration_Services

    Here as well: http://msdn.microsoft.com/en-us/library/ms141026.aspx

    I hope that helps!

  12. Jerie

    Thanks phouseak, Nice article,
    May I request the package file (.dtsx) of this article ?

    • phouseak

      Jerie, that’s entirely possible. Do you want me to email the address you used in the comment? Thanks.

  13. Diana

    Wonderful! It worked perfectly! thank-you

  14. Eric

    Wonderful article – very well laid out. Thanks!

  15. Aniruddh

    You have really made everything clear about building such packages. To me SSIS looks one big task that requires brain to put all puzzle pieces together and then see everything in Green 🙂

    Really going through books wont give as much as knowledge as much going through blogs. May be its almost impossible to get cookbook for SSIS

  16. Amar

    This explanation is amazing. It’s becomes really easy to follow because of all the screen shots used. Thank You,

    But it becomes really difficult if the source file is a flat file and we are not allowed to save the flat file data into a relational table ??? 😉

  17. sp

    got it. Thanks. 🙂

  18. Sravani

    I think this is a great example….

  19. vivek

    Hi,

    I have one problem in my package when i specified expression what you said,it raise an error.

    • phouseak

      Vivek,
      Can you recreate the error and paste the error text into the comments here? Thanks.

  20. ramesh

    Hi
    I am getting following error. Can u please help me.

    [Execute SQL Task] Error: There is an invalid number of result bindings returned for the ResultSetType: “ResultSetType_Rowset”.

    • ravi

      I get the same error as Ramesh. How do I get over it?

  21. phouseak

    Is your value type for the result set an Object type?

    • ravi

      I am not sure if I understood your question correctly, but I created two variables with the result name as zero “0” for both of them and one is an object datatype and other is a string datatype. The name of the variables are ObjBillerSet and StringBillerID. Also if possible do you have package where you create excel output instead of csv?

      Thank you very much. This was really helpful.

  22. Tony

    This is great. How about if I want to do the same (Create multiple Flat Files) but from a single stored procedure that only runs once?

Leave a comment