SQL DB Collection

SQL – RDBMS – Business Intelligence – OLAP – Data Warehouse – SSIS – SSAS

Dynamic SQL in SQL Server Integration Services (SSIS)

Posted by sqldb on June 21, 2006

http://www.vsteamsystemcentral.com/cs/blogs/applied_team_system/archive/2006/05/07/71.aspx

I sometimes miss the Dynamic Properties Task in DTS. I used it for all sorts of functionality – and I’m struggling to replace some of that flexibility in complex SSIS development.

I recently developed a package with dynamic SQL serving as the data source for a Data Flow. I accepted the mission and here’s an example to demonstrate how I accomplished this:


Drag a Data Flow Task onto the Control Flow canvas:

Double-click the Data Flow task to edit it. Drag a DataReader Source onto the Data Flow canvas and double-click it for editing. The Advanced Editor opens. Select or create an ADO.Net connection manager on the Connection Managers tab:

On the Component Properties tab, enter an SQL Statement in the SqlCommand property (I query a table I created named dbo.TestTable which contains three columns: TestID [Identity PK], TestName [VarChar(20)], and TextValue [int]):

Verify the SqlCommand field names on the Column Mappings tab:

Drag a Flat File Destination onto the Data Flow canvas and (this is important) connect the output of the DataReader Source to the Flat File Destination with a precendence constraint (green arrow):

Double-click the Flat File Destination to edit it. On the Connection Manager page, click the New button to create a new Flat File Connection Manager:

Assign the Flat File Connection Manager a name (I used “OutFile”) on the General page. Enter a filename (“OutFile.txt”) and specifics regarding collation and row delimiters:

Click Columns to configure column details.

Why? I always create Flat File Connection Managers for new files from the Flat File Destination task. If the target file does not exist, the Destination task has no better way to know which columns to expect.

Note the Preview grid displays the expected columns (read from the DataReader Source via the precendence constraint connector):

Click OK to create the Connection Manager and return to the Flat File Destination Editor:

Click the Mappings item in the page list to view (and auto-map) the DataReader Source columns to the Flat File Destination columns:

Return to the Control Flow tab and click any empty space on the Control Flow canvas.

Why? You are about to create a new Variable. Unlike DTS variables (which were all global in scope), SSIS variables have specific scope. Scope is determined, for better or worse, by the Task or SSIS Object that has focus when you create a new variable. I say “for better or worse” because I’ve not yet discovered a method for changing variable scope during the variable creation process. Clicking on the Control Flow canvas gives it focus, and Package-scoped (global) variables may then be created.

Click View, then Other Windows, then Variables to display the Variables dialog. Set the Data Type to String and enter some query in the Value field. Note: the query used here must expose the same columns as the query in the SqlCommand property of the DataReader Source or the Data Flow will fail during pre-execution package validation (There is most likely a method to address this – more later, perhaps…). I created a variable named SQLOut with a default value of “SELECT 0 AS TestID, ‘Zero’ AS TestName, 0 AS TestValue”:

Drag a Script Task onto the Data Flow canvas. Connect it via precendence constraint (green arrow) to the Data Flow task as shown:

Double-click the Script Task to open the Script Task Editor. Click on Script in the page list and add the variable name created earlier (SQLOut) to the ReadWriteVariables property:

Click the Design Script button to open the Visual Studio for Applications (VSA) Script Editor. Enter the following script in the Main subroutine of the ScriptMain class:

MsgBox(Dts.Variables(“SQLOut”).Value)

Dts.Variables(“SQLOut”).Value = “SELECT 1 AS TestID, ‘Unos’ AS TestName, 12 AS TestValue”

MsgBox(Dts.Variables(“SQLOut”).Value)

Dts_TaskResult = Dts_Results_Success

To test, close the VSA Editor and click the OK button to close the Script Task Editor. Right-click the Script Task and click Execute Task:

The first MsgBox command should execute displaying the default contents of the SQLOut variable:

Click the OK button. The second MsgBox command should display the updated SQLOut variable contents:

Click the OK button. The Script task should complete without error:

Click the Stop button to exit Debug mode.

Right-click the Data Flow task and click Properties to display the Data Flow Task properties:

In the Properties dialog, click Expressions and then click the ellipsis:

The Property Expressions Editor displays. Select “[DataReader Source].[SqlCommand]” from the Property dropdown list and click the ellipsis beside Expression:

The Expression Builder displays. Expand the Variables item in the treeview and scroll through the list until “User::SQLOut” is located. Drag this into the Expression textbox on the lower part of the Expression Builder page:

Click the OK button. “@[User::SQLOut]” is now assigned to the “[DataReader Source].[SqlCommand]” property:

Click the OK button to close the Expressions dialog and proceed:

To test, press F5 or click the Play button:

Navigate to and open the flat file created earlier (OutFile.txt) to view the results:

:{> Andy

About these ads

12 Responses to “Dynamic SQL in SQL Server Integration Services (SSIS)”

  1. Olivier said

    THANK YOU VERY MUCH!!!!!!!!!!!!

  2. Stephan said

    Thanks!

    What I need is this part…

    “Note: the query used here must expose the same columns as the query in the SqlCommand property of the DataReader Source or the Data Flow will fail during pre-execution package validation (There is most likely a method to address this – more later, perhaps…)”

    I have a dynamic SQL SELECT statement, but the columns change every time (in a for each loop), so I get the column mapping error. Any ideas where I can go to find something on this?

  3. cenko2 said

    And on thesame note, how do we pass a parameter in the dynamic SQL?

  4. Lynden said

    How do extract data with the datareader source with a date variable

  5. ruby said

    I am facing the same problem as Stephan .

    Please suggest some ideas.

    Regards,

  6. Mark said

    Pure brilliance – exactly what I needed to read. By adding variables you can build any kind of SQL statement!

  7. dave said

    Thanks, Gracias hermano, era lo que necesitaba…………

  8. Global SMT & Packaging magazine for electronics assembly and advanced packaging professionals….

    [...]Dynamic SQL in SQL Server Integration Services (SSIS) « SQL DB Collection[...]…

  9. I really speculate the reasons why you labeled this particular blog post,
    “Dynamic SQL in SQL Server Integration Services
    (SSIS) SQL DB Collection”. In any event I actually adored the
    blog!Many thanks-Melvina

  10. Hi there I am so

    delighted I found your blog page, I really found you by

    accident, while I was researching on Google for something

    else, Anyways I am here now and would just like to say cheers for a fantastic post and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to

    browse it all at the moment but I have bookmarked it and also

    added in your RSS feeds, so when I have time I will be
    back to read a lot more, Please do keep up the fantastic job.

  11. I have been surfing online more than 3 hours today, yet I never found any interesting article

    like yours. It’s pretty worth enough for me. Personally, if all webmasters and
    bloggers made good content as you did, the internet will be a

    lot more useful than ever before.

  12. Admiring the hard work you put into your

    website and detailed information you present. It’s great to come

    across a blog every once in a while that isn’t the same out of date rehashed

    information. Fantastic read! I’ve bookmarked your site and I’m including your

    RSS feeds to my Google account.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: