[Forum FAQ] How do I send multiple rows returned by Execute SQL Task as Email content in SQL Server Integration Services?

Question:
There is a scenario that users want to send multiple rows returned by Execute SQL Task as Email content to send to someone. With Execute SQL Task, the Full result set is used when the query returns multiple rows, it must map to a variable of the Object data
type, then the return result is a rowset object, so we cannot directly send the result variable as Email content. Is there a way that we can extract the table row values that are stored in the Object variable as Email content to send to someone?
Answer:
To achieve this requirement, we can use a Foreach Loop container to extract the table row values that are stored in the Object variable into package variables, then use a Script Task to write the data stored in packages variables to a variable, and then set
the variable as MessageSource in the Send Mail Task. 
Add four variables in the package as below:
Double-click the Execute SQL Task to open the Execute SQL Task Editor, then change the ResultSet property to “Full result set”. Assuming that the SQL Statement like below:
SELECT   Category, CntRecords
FROM         [table_name]
In the Result Set pane, add a result like below (please note that we must use 0 as the result set name when the result set type is Full result set):
Drag a Foreach Loop Container connects to the Execute SQL Task. 
Double-click the Foreach Loop Container to open the Foreach Loop Editor, in the Collection tab, change the Enumerator to Foreach ADO Enumerator, then select User:result as ADO object source variable.
Click the Variable Mappings pane, add two Variables as below:
Drag a Script Task within the Foreach Loop Container.
The C# code that can be used only in SSIS 2008 and above in Script Task as below:
public void Main()
   // TODO: Add your code here
            Variables varCollection = null;
            string message = string.Empty;
            Dts.VariableDispenser.LockForWrite("User::Message");
            Dts.VariableDispenser.LockForWrite("User::Category");
            Dts.VariableDispenser.LockForWrite("User::CntRecords");     
            Dts.VariableDispenser.GetVariables(ref varCollection);
            //Format the query result with tab delimiters
            message = string.Format("{0}\t{1}\n",
                                        varCollection["User::Category"].Value,
                                        varCollection["User::CntRecords"].Value
           varCollection["User::Message"].Value = varCollection["User::Message"].Value + message;   
           Dts.TaskResult = (int)ScriptResults.Success;
The VB code that can be used only in SSIS 2005 and above in Script Task as below, please note that in SSIS 2005, we should
change PrecompileScriptIntoBinaryCode property to False and Run64BitRuntime property to False
Public Sub Main()
        ' Add your code here
        Dim varCollection As Variables = Nothing
        Dim message As String = String.Empty
        Dts.VariableDispenser.LockForWrite("User::Message")
        Dts.VariableDispenser.LockForWrite("User::Category")
        Dts.VariableDispenser.LockForWrite("User::CntRecords")
        Dts.VariableDispenser.GetVariables(varCollection)
        'Format the query result with tab delimiters
        message = String.Format("{0}" & vbTab & "{1}" & vbLf, varCollection("User::Category").Value, varCollection("User::CntRecords").Value)
        varCollection("User::Message").Value = DirectCast(varCollection("User::Message").Value,String) + message
        Dts.TaskResult = ScriptResults.Success
End Sub
Drag Send Mail Task to Control Flow pane and connect it to Foreach Loop Container.
Double-click the Send Mail Task to specify the appropriate settings, then in the Expressions tab, use the Message variable as the MessageSource Property as below:
The final design surface like below:
References:
Result Sets in the Execute SQL Task
Applies to:
Integration Services 2005
Integration Services 2008
Integration Services 2008 R2
Integration Services 2012
Integration Services 2014
Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

Thanks,
Is this a supported scenario, or does it use unsupported features?
For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
in a supported way?
Thanks! Josh

Similar Messages

  • [Forum FAQ] How do I send an email to users when the data in the report have been changed in Reporting Services?

    Introduction
    There is a scenario that the data in the report changes infrequently, so the users want to be informed and get the most updated data once the data changes. By default, report server always run the report with the most recent data. Is there a way that we
    can subscribe the report, so that we can send an email to users when the data in the report has been changed?
    Solution
    To achieve this requirement, we can create a subscription for the report, then create a trigger in the table which including the report data. When this table has data insert, update or delete, it will be triggered and execute the subscription to send email
    to users.
    In the Report Manager, create a subscription for the report and make it only execute one time.
    When we create a subscription, a corresponding SQL Agent job will be created. Then we can use the query below to find out the job based on ScheduleId:
    -- List all SSRS subscriptions
    USE [ReportServer];  -- You may change the database name.
    GO 
    SELECT USR.UserName AS SubscriptionOwner
          ,SUB.ModifiedDate
          ,SUB.[Description]
          ,SUB.EventType
          ,SUB.DeliveryExtension
          ,SUB.LastStatus
          ,SUB.LastRunTime
          ,SCH.NextRunTime
          ,SCH.Name AS ScheduleName   
              ,RS.ScheduleId
          ,CAT.[Path] AS ReportPath
          ,CAT.[Description] AS ReportDescription
    FROM dbo.Subscriptions AS SUB
         INNER JOIN dbo.Users AS USR
             ON SUB.OwnerID = USR.UserID
         INNER JOIN dbo.[Catalog] AS CAT
             ON SUB.Report_OID = CAT.ItemID
         INNER JOIN dbo.ReportSchedule AS RS
             ON SUB.Report_OID = RS.ReportID
                AND SUB.SubscriptionID = RS.SubscriptionID
         INNER JOIN dbo.Schedule AS SCH
             ON RS.ScheduleID = SCH.ScheduleID
    ORDER BY USR.UserName
             ,SUB.ModifiedDate ;
    Create a trigger in the table which including the report data.
    CREATE TRIGGER reminder
    ON test.dbo.users
    AFTER INSERT, UPDATE, DELETE
    AS
    exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
    Please note that the command ‘exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'’ is coming from the job properties. We can go to SQL Server Agent Jobs, right-click the corresponding job to open
    the Steps, copy the step command, and then paste it to the query.
    Then when the user table has data insert, update or delete, the trigger will be triggered and execute the subscription to send email to users.
    References:
    Subscriptions and Delivery (Reporting Services)
    Internal Working of SSRS Subscriptions
    SQL Server Agent
    Applies to:
    Reporting Services 2005
    Reporting Services 2008
    Reporting Services 2008 R2
    Reporting Services 2012
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Thanks,
    Is this a supported scenario, or does it use unsupported features?
    For example, can we call exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='b64ce7ec-d598-45cd-bbc2-ea202e0c129d'
    in a supported way?
    Thanks! Josh

  • [Forum FAQ] How do I have Invoke-SqlCmd return a date value without adding time

    Introduction
    A select statement executed from Invoke-SqlCmd returns a value from a Date column, the value has "12:00:00 AM" appended.  The same select statement executed within SQL Server Management Studio displays the date properly without any time formatting.
    Sample data is as follows:
    How to have Invoke-SqlCmd return Date values without adding time for multiple Date type columns and pipe the output into CSV file?
    Solution
    In SQL Server 2012 or onwards, use the FORMAT() function to convert datetime values to date format when executing query from Invoke-SqlCmd. In earlier versions such as SQL Server 2008 R2, use the traditional CONVERT() function to format datetime values to
    different date formats(yyyy.mm.dd, mm/dd/yyyy, etc) when executing query from Invoke-SqlCmd. Then pipe the output of SQL query result into CSV file by specifying export-csv parameter. An example is as follows.
    Create a table named “Test_invokesqlcmd” that contains Date type columns in SQL Server.
    USE Test
    Go
    CREATE TABLE [dbo].[Test_invokesqlcmd](
        [id] [int] NOT NULL,
        [name] [varchar](20) NULL,
        [test1] [date] NULL,
        [test2] [date] NULL
    ) ON [PRIMARY]
    GO
    insert into [dbo].[Test_invokesqlcmd]
    values(1,'David','2014-10-15','2015-01-07'),(2,'Jane','2011-08-05','2012-11-7'),(3,'Crystal','2013-09-15','2010-02-24')
    Define a query string, execute it from Invoke-SqlCmd and save the query result to a CSV file.
    Scripts for SQL Server 2012:
    $query1 = @"
        use Test;
        SELECT FORMAT(test1,'d') as newtest1, FORMAT(test2,'d') as newtest2 from dbo.Test_invokesqlcmd
    write-host $query1
    Invoke-Sqlcmd -Query $query1 -ServerInstance localhost | export-csv -notypeinformation -path c:\Files\test.csv
    Scripts for SQL Server 2008 R2:
    $query2 = @"
        Use Test;
        SELECT CONVERT(varchar, test1, 102) as newtest1,CONVERT(varchar, test2, 102) as newtest2
        FROM dbo. Test_invokesqlcmd
    write-host $query2
    Invoke-Sqlcmd -Query $query2 -ServerInstance localhost | export-csv -notypeinformation -path c:\Files\test.csv
    Check the results in SQL Server PowerShell window and csv file.
    SQL Server 2012:
    SQL Server 2008 R2:
    Reference
    Using the Invoke-Sqlcmd cmdlet
    SQL Server Functions that helps to convert date and time values to and from string literals and other date and time formats
    Applies to
    SQL Server 2014
    SQL Server 2012
    SQL Server 2008 R2
    SQL Server 2008
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Cross posted. More appropriate in JSF forum so continue conversation there.
    http://forum.java.sun.com/thread.jspa?threadID=717292&messageID=4142615#4142615

  • How can I use multiple row insert or update into DB in JSP?

    Hi all,
    pls help for my question.
    "How can I use multiple rows insert or update into DB in JSP?"
    I mean I will insert or update the multiple records like grid component. All the data I enter will go into the DB.
    With thanks,

    That isn't true. Different SQL databases have
    different capabilities and use different syntax, That's true - every database has its own quirks and extensions. No disagreement there. But they all follow ANSI SQL for CRUD operations. Since the OP said they wanted to do INSERTs and UPDATEs in batches, I assumed that ANSI SQL was sufficient.
    I'd argue that it's best to use ANSI SQL as much as possible, especially if you want your JDBC code to be portable between databases.
    and there are also a lot of different ways of talking to
    SQL databases that are possible in JSP, from using
    plain old java.sql.* in scriptlets to using the
    jstlsql taglib. I've done maintenance on both, and
    they are as different as night and day.Right, because you don't maintain JSP and Java classes the same way. No news there. Both java.sql and JSTL sql taglib are both based on SQL and JDBC. Same difference, except that one uses tags and the other doesn't. Both are Java JDBC code in the end.
    Well, sure. As long as you only want to update rows
    with the same value in column 2. I had the impression
    he wanted to update a whole table. If he only meant
    update all rows with the same value in a given column
    with the same value, that's trivial. All updates do
    that. But as far as I know there's know way to update
    more than one row where the values are different.I used this as an example to demonstrate that it's possible to UPDATE more than one row at a time. If I have 1,000 rows, and each one is a separate UPDATE statement that's unique from all the others, I guess I'd have to write 1,000 UPDATE statements. It's possible to have them all either succeed or fail as a single unit of work. I'm pointing out transaction, because they weren't coming up in the discussion.
    Unless you're using MySQL, for instance. I only have
    experience with MySQL and M$ SQL Server, so I don't
    know what PostgreSQL, Oracle, Sybase, DB2 and all the
    rest are capable of, but I know for sure that MySQL
    can insert multiple rows while SQL Server can't (or at
    least I've never seen the syntax for doing it if it
    does).Right, but this syntax seems to be specific to MySQL The moment you use it, you're locked into MySQL. There are other ways to accomplish the same thing with ANSI SQL.
    Don't assume that all SQL databases are the same.
    They're not, and it can really screw you up badly if
    you assume you can deploy a project you've developed
    with one database in an environment where you have to
    use a different one. Even different versions of the
    same database can have huge differences. I recommend
    you get a copy of the O'Reilly book, SQL in a
    Nutshell. It covers the most common DBMSes and does a
    good job of pointing out the differences.Yes, I understand that.
    It's funny that you're telling me not to assume that all SQL databases are the same. You're the one who's proposing that the OP use a MySQL-specific extension.
    I haven't looked at the MySQL docs to find out how the syntax you're suggesting works. What if one value set INSERT succeeds and the next one fails? Does MySQL roll back the successful INSERT? Is the unit of work under the JDBC driver's control with autoCommit?
    The OP is free to follow your suggestion. I'm pointing out that there are transactions for units of work and ANSI SQL ways to accomplish the same thing.

  • How can I send multiple photos in an email?

    How can I send multiple photos in an email?

    In Photos, when looking at your pictures, click the Action arrow first (upper right), before selecting any pictures.  Then you can tap select the pictures you want to send then click "Share" in the upper left.  From there you can Email.
    If you click and open one picture first, the Action button will only allow you to share that one picture.
    (Yeah, took me a while to figure this out. )
    ivan

  • How can we send multiple attachments in a mail from iPad 2

    Hi,
    I am using a ipad2. I want to know how we can send multiple attachments through mail from iPad. I did not find any option of doing this. Is there a way to do this.
    Regards,
    Satyabrat

    You can't do it natively on the iPad (unless you just want to send up to 5 photos from the Photos app). I use the GoodReader app which supports quite a few document/file types (e.g. PDF, Excel, Word, pictures), and from that I can select multiple files (including different types) and attach them to the same email.

  • How can i send multiple films from iMovie06HD to iDVD? ( iDVD gave me ****)

    After 2 weeks of jerky videos, unexpected shutdowns, multiplex and buring errors i yesterday finally had something. Than i noticed, that the chapters didn't work. Allright, i thought, those 5-min chapter-marks are a mess anyway. I got myself iMovie06HD to finally set the markers myself.
    My Problem: I have got four films to burn on that dvd. Each of which is about half an hour and i want them to be on that dvd as four single films with own chapter menues.
    How can i send multiple films to iDVD from iMovie06HD? All i found was "only send selected clips" which i did but then my four single films arrive at iDVD as ONE whole film, with chapters yes - but there is no way to create a menu with four single films. I tried all i could imagine. I tried to solve the problem by creating four iMovie projects which will also create four corresponding iDVD projects. I tried to export the movies in multiple formats but then the chapter markers seem to be gone.
    I have to admit i'm desperate. I hope i made my problem clear to you and somebody knows a solution. Thank you! Cheers, Matthias

    Just drag and drop each iMovie project on to the iDVD menu - being careful to avoid any of the drop zones.

  • How can I send multiple string commands into a VISA write?

    Hi Fellow LabVIEW users
    I am very new to LabVIEW (2.5 months) so please forgive me if my lingo is not up to par.
    How can I send multiple string commands to a VISA write. For example each string command looks like this
    1) 3A00 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0033 (Scenario 1)
    2) 3A01 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0034 (Scenario 2)
    3) 3A01 0000 0000 33FF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0067 (Scenario 3).
    and so on and so forth. And there are a number of scenarios.
    Each String scenario will give a different string output which will be interpreted differently in the front panel.
    Right now I have to manually change the string commands on the front panel to give me the desired output. How can I do this without manually changing the commands i.e. hard coding each scenario into the block diagram?
    Thanks, any feedback will help.
    mhaque

    Please stick to your original post.

  • How can i send multiple sms from my iphone 4

    how can i send multiple sms from my i phone 4

    Turn Group Messaging (instructions in lin that follows) off and send the message to multiple recipients. The result may be dependent on your carrier. If manually keying in numbers rather than using contacts, use the return key after each number. http://support.apple.com/kb/HT5760

  • How can I send multiple pics to email from my iPhone 5

    How can I send multiple pics from photos app on I phone 5 to an e mail?

    Open the album or event folder on your iPhone.  Click the "arrow" icon in the upper right side of your screen.
    Click the pictures you'd like to share via email (they will show a little checkmark when selected).
    Click the "share button at the lower left corner of your screen...
    Taa daa!
    Bob

  • How do I add multiple rows in Numbers for iPad?

    how do I add multiple rows in Numbers for iPad?

    Hi James,
    On the iPod I can only insert what is on the clipboard but I can insert however many rows I have there. Is it working differently for you? Benjoon seemed to think that he could not do this in Numbers. He was ruling Numbers out because of it. He doesn't need to do that because of this issue.
    If I was needing to insert multiple blank rows often I might keep a table of blank rows or just some blank rows at the end of the working table that I could copy/paste. This is no different than Numbers on the Mac.
    quinn

  • How do I insert multiple rows from a single form ...

    How do I insert multiple rows from a single form?
    This form is organised by a table. (just as in an excel format)
    I have 20 items on a form each row item has five field
    +++++++++++ FORM AREA+++++++++++++++++++++++++++++++++++++++++++++++++++++
    +Product| qty In | Qty Out | Balance | Date +
    +------------------------------------------------------------------------+
    +Item1 | textbox1 | textbox2 | textbox3 | date +
    + |value = $qty_in1|value= &qty_out1|value=$balance1|value=$date1 +
    +------------------------------------------------------------------------+
    +Item 2 | textbox1 | textbox2 | textbox4 | date +
    + |value = $qty_in2|value= $qty_out1|value=$balance2|value=$date2 +
    +------------------------------------------------------------------------+
    + Item3 | textbox1 | textbox2 | textbox3 | date +
    +------------------------------------------------------------------------+
    + contd | | | +
    +------------------------------------------------------------------------+
    + item20| | | | +
    +------------------------------------------------------------------------+
    + + + SUBMIT + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Database Structure
    +++++++++++++++++
    + Stock_tabe +
    +---------------+
    + refid +
    +---------------+
    + item +
    +---------------+
    + Qty In +
    +---------------+
    + Qty Out +
    +---------------+
    + Balance +
    +---------------+
    + Date +
    +++++++++++++++++
    Let's say for example user have to the use the form to enter all 10 items or few like 5 on their stock form into 4 different textbox field each lines of your form, however these items go into a "Stock_table" under Single insert transaction query when submit button is pressed.
    Please anyone help me out, on how to get this concept started.

    Hello,
    I have a way to do this, but it would take some hand coding on your part. If you feel comfortable hand writing php code and doing manual database calls, specificaly database INSERT calls you should be fine.
    Create a custom form using the ADDT Custom Form Wizard that has all the rows and fields you need. This may take a bit if you are adding the ability for up to 20 rows, as per your diagram of the form area. The nice thing about using ADDT to create the form is that you can setup the form validation at the same time. Leave the last step in the Custom Form Wizard blank. You can add a custom database call here, but I would leave it blank.
    Next, under ADDT's Forms Server Behaviors, select Custom Trigger. At the Basic tab, you enter your custom php code that will be executed. Here you are going to want to put your code that will check if a value has been entered in the form and then do a database INSERT operation on the Stock_table with that row. The advanced tab lets you set the order of operations and the name of the Custom Trigger. By default, it is set to AFTER. This means that the Custom Trigger will get executed AFTER the form data is processed by the Custom Form Transaction.
    I usually just enter TEST into the "Basic" tab of the Custom Trigger. Then set my order of operations in the "Advanced" tab and close the Custom Trigger. Then I go to the code view for that page in Dreamweaver and find the Custom Trigger function and edit the code manually. It's much easier this way because the Custom Trigger wizard does not show you formatting on the code, and you don't have to keep opening the Wizard to edit and test your code.
    Your going to have to have the Custom Trigger fuction do a test on the submitted form data. If data is present, then INSERT into database. Here's a basic example of what you need to do:
    In your code view, the Custom Trigger will look something like this:
    function Trigger_Custom(&$tNG) {
    if($tNG->getColumnValue("Item_1")) {
    $item1 = $tNG->getColumnValue("Item_1");
    $textbox1_1 = $tNG->getColumnValue("Textbox_1");
    $textbox1_2 = $tNG->getColumnValue("Textbox_2");
    $textbox1_3 = $tNG->getColumnValue("Textbox_3");
    $date1 = $tNG->getColumnValue("Textbox_3");
    $queryAdd = "INSERT INTO Stock_table
    (item, Qty_In, Qty_Out, Balance, Date) VALUES($item1, $textbox1_1, $textbox1_2, $textbox1_3, $date1)"
    $result = mysql_query($queryAdd) or die(mysql_error());
    This code checks to see if the form input field named Item_1 is set. If so, then get the rest of the values for the first item and insert them into the database. You would need to do this for each row in your form. So the if you let the customer add 20 rows, you would need to check 20 times to see if the data is there or write the code so that it stops once it encounters an empty Item field. To exit a Custom Trigger, you can return NULL; and it will jump out of the function. You can also throw custom error message out of triggers, but this post is already way to long to get into that.
    $tNG->getColumnValue("Item_1") is used to retrieve the value that was set by the form input field named Item_1. This field is named by the Custom Form Wizard when you create your form. You can see what all the input filed names are by looking in the code view for something like:
    // Add columns
    $customTransaction->addColumn("Item_1", "STRING_TYPE", "POST", "Item_1");
    There will be one for each field you created with the Custom Form Wizard.
    Unfortunately, I don't have an easy way to do what you need. Maybe there is a way, but since none of the experts have responded, I thought I would point you in a direction. You should read all you can about Custom Triggers in the ADDT documentation/help pdf to give you more detailed information about how Custom Triggers work.
    Hope this helps.
    Shane

  • How can I send multiple pictures to the Kodak link (under file & then order prints)? if the photos are not sequential can it be done?

    how can I send multiple pictures to the Kodak link (under file & then order prints)?  if the photos are not sequential can it be done?

    Does the order matter here?Because the photos will be sent for printing. If there is any other reason, can you please cite example.

  • How to send multiple data files / music files using bluetooth / whatsapp / emails...

    hello everyone,,,
    is there any option to send multiple data files / music files using bluetooth / whatsapp / emails...
    as option to select multiple files using "SELECT in menu option / left aA"+ scroll tracepad" is availble with pictures only.
    and while receiving files via bluetooth i'm unable to do any other activity.

    One at time, via Bluetooth.
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • How to retrieve the multiple rows data on PDF form in a web service method using WSDL DataConnection

    How to retrieve the multiple rows data on PDF form in a web service method using WSDL DataConnection.
    I have a multiple rows on PDF form. All rows have 4 textfields. I want to submit the multiple rows data to a method defiened in webservice.
    Unable to retrieve the data in multiple rows within webservice method.

    Hi Paul,
    I'm now able to save the retrieved xml in a hidden text field and create dynamic table, and I'm able to fill this table from the XML, but the problem is that I could not find the correct way to loop on the xml, what I'm trying to say, the table will have number of rows with the data of the first row only, so can you tell me the right way to loop on the xml!
    this is my code
    TextField1.rawValue=xmlData.document.rawValue;
    xfa.datasets.data.loadXML(TextField1.rawValue, true, false);
    for(var i=0; i<count; i++)
    xfa.form.resolveNode("form1.P1.Table1.Row1["+i+"].Num").rawValue = xfa.datasets.data.record.num.value;
    xfa.form.resolveNode("form1.P1.Table1.Row1["+i+"].Name").rawValue = xfa.datasets.data.record.name.value;
    Table1.Row1.instanceManager.addInstance(true);
    Thanks
    Hussam

Maybe you are looking for