SSIS Execute SQL Task using sp_rename giving deadlock issues

All,
We have a job that has 2 steps and both of those steps call an SSIS package
1st package - Loads the data from a SQL server source, to a SQL Server destination tables, say, "TblHistory" is one of them
2nd package - It does a re-name from the History table to the Main table, so below, is how the code looks like in the execute SQL Task:
BEGIN TRANSACTION
EXECUTE sp_rename 'dbo.Tbl', 'TblOld'
EXECUTE sp_rename N'dbo.TblOld.PK_TblId', N'PK_TblIdOld', N'INDEX'
EXECUTE sp_rename 'dbo.TblHistory', 'Tbl'
EXECUTE sp_rename N'dbo.Tbl.PK_TblHistoryId', N'PK_TblId', N'INDEX'
EXECUTE sp_rename 'dbo.TblOld', 'TblHistory'
EXECUTE sp_rename N'dbo.TblHistory.PK_TblIdOld', N'PK_TblHistoryId', N'INDEX'
COMMIT TRANSACTION
In package 1 there are multiple history tables that are being loaded and most of them get renamed in the 2nd package. There is a separate SQL task for each of the history tables. The problem that I am running in to are the deadlock issues. When the 2nd package
runs, it throws this error:
"SQL - Table Rename & Swap for "Tbl" Execute SQL Task     Description: Executing the query "BEGIN TRANSACTION     EXECUTE sp_rename Tbl..." failed with the following error: "Transaction
(Process ID 60) was deadlocked on lock resources with another process and has been chosen as the deadlock victim."
It's giving me a deadlock issue on the other tasks as well. So, when the job ran today, I am noticing 4 deadlock errors on the 4 different execute SQL tasks in the 2nd package (i.e. the job fails at 2nd step)
Has anyone faced this scenario before?

Why renaming tables? The data do not change. So just load the data to an interim table and push it to the target or may be you do not need it at all - just load the right table.
I admit I fail to capture the overall picture of what you are trying to solve or deliver. But renaming tables is something not usual.
Arthur My Blog

Similar Messages

  • How to pass a parameter into execute sql task and later use it into dataflow task?

    i am in a situation, where i have a logging table in which i have a primary key called ETL_log_ID which is an identity column and acts as a foreign key for various fact table and dimension tables which are populated using SSIS packages. Now i wanna use the
    ETL_log_ID as a parameter in the execute sql task which populates the log table and pass the same value in the data flow task which populates the facts and dimension. Can you let me know how to pass the parameter in a step by step procedure.
    Thanks,
    Nikhil
      

    Nikhil,
    You can check the following :
    http://www.programmersedge.com/post/2013/03/05/ssis-execute-sql-task-mapping-parameters-and-result-sets.aspx
    http://stackoverflow.com/questions/7610491/how-to-pass-variable-as-a-parameter-in-execute-sql-task-ssis
    Regarding the usage in Dataflow task, Can you elaborate on that a little?
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Same parameter multiple times in Execute SQL Task

    Hi all,
    i have a fairly long parametrized query that needs to be run within an Execute SQL task. It has only 2 unique parameters, but these need to be used multiple within that query. The connection is OLEDB.
    ill simplify my requirement by making up an arbitrary T-SQL "where" clause that will illustrate what i need:
    where
    x = @param1
    and y = @param1
    and z > @param2
    and w > @param2
    moving this into an SSIS execute SQL task will require the following:
    where
    x = ?
    and y = ?
    and z > ?
    and w > ?
    I know i need to specify 4 parameters and remap the same variables multiple times.. like so:
    User:aram1   -> 0
    User:aram1   -> 1
    User:aram2   -> 2
    User:aram2   -> 3
    isnt there a better way? i ask this because in my real task i have 2 params, each is reused 4 and 5 times respectively and it seems stupid to repeat params like this.

    @ _proffy_
    you can pass the same variable or value as parameter multiple times sql task.
    follow the steps below.
    1) type the sql query with parameters in SQL statement tab of sql task editor
    2. in the parameter mapping, select the variables.
      you can select the same variables more than once.
     give the parameter name as 0,1,2,3..... based on variables you require.
    do not forget to chooose the appropriate Datatype.
    ex:
    select * from table1
    where a= ?
    and b=?
    and c= ?
    parameters:
    Var name               param Name
    user::Var1               0   
    user::Var1               1
    user::Var2               2
    so the value becomes a=var1, b= var1 and c= var2

  • SSIS: How to use one Variable as Input and Output Parameter in an Execute SQL Task

    Hello,
    i need your help,I'm working on this issue since yesterday and have no idea how to deal with it.
    As I already said in the tilte i want to start a stored procedure via a Execute SQL Task which has around 15 prameters. 10 of these should be used as input AND output value.
    As an example:
    i have three  Variable:
    var1    int        2
    var2    int     100
    var3    int     200
    the stroed procedure:
       sp_test
          @var1 int
          @var2 int output
          @var3 int output
       AS
       BEGIN
            SET @var2 = @var2 * @var1
            SET @var3 = @var3 + @var1
       END
    So in the Execute SQL Task i call the Stored Procedure as follwos:
        Exec sp_test  @var1 = ?, @var2 = ? output, @var3 = ? output
    (I use an OLE DB Connection)
    The parameter mapping is as follows:
    User::Var1        input                   numeric              0                 -1
    User::Var2        input/output         numeric              1                 -1
    User::Var3        input/output         numeric              2                 -1
    Now my problem. If i set  Var2 and Var3 as Input parameter the values are still the same after running the package. If i set them to a output value the are both Null because the procedure doesnt get any values.
    I already tried to list them a second time - like
        User::Var2        input                  numeric              1                 -1
        User::Var2        output                 numeric              1                 -1
    or i use a new variable
        User::Var2                  input                  numeric              1                 -1
        User::Var2Return        output                 numeric              1                 -1
    but i alwas get the error
    "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
    Has anybody an idea how I can solve this problem?
    Thanks a lot.
    Kind Regards,
    Alice

    Hi Alain,
    thx for your answer.
    I have around 15 procedures called one after the other to calculated and modify my values. Each procedure is responsible for an other but overlapping set of variables. So i thought it would be a good idea to call them one after the other with the needed variables via a execute sql task.
    So if i use a result set, how i get my stored procedure to return 10 values? I would have to use a Function instead of a procedure, wouldn't i?
    As if i have 15 procedures this would be a lot of work.
    But thanks a lot for the idea. I think an other idea would be to create one function which calls all stored procedures and returns all the calculated values as a result set, wouldn't it?.
    Kind Regards.
    Alice

  • SSIS - Using Variables in Execute SQL Task Error

    The following query in my Execute SQL Task throws the following error when run - [Execute SQL Task] Error: Executing the query "SELECT @columnz = COALESCE(@columnz + ',[' + times..." failed with the following error: 
    "Must declare the scalar variable "@columnz".". Possible failure reasons: Problems with the query, 
    "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
    Query:
    drop table tmpNCPCNCDownstreamMaxUtilization3wks
    select node, max(utilization) as max_Utilization, DATE
    into tmpNCPCNCDownstreamMaxUtilization3wks
    from stage_ncpcncdownstream_temporal
    WHERE Date BETWEEN DATEADD(day, -20, GETDATE()) AND GETDATE() 
    group by node, date
    order by node
    go
    alter table tmpNCPCNCDownstreamMaxUtilization3wks add Timestamp varchar(50)
    go
    update tmpNCPCNCDownstreamMaxUtilization3wks
    set Timestamp = 'WeekOf_' + cast(left(Date, 11) as varchar)
    go
    --drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
    --go
    declare @columnz varchar (8000)
    go
    SELECT @columnz = COALESCE(@columnz + ',[' + timestamp + ']','[' + timestamp+ ']')
    FROM tmpNCPCNCDownstreamMaxUtilization3wks group by timestamp order by timestamp
    go
    --pivot contents in @columns
    declare @query varchar(8000)
    SET @query ='select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from 
    (select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
    pivot
    sum(max_Utilization) for timestamp in('+ @columnz +')
    )as p'
    execute (@query)
    --empty contents from NCPCNCDownstreamMaxUtilization3wks
    update tmpNCPCNCDownstreamMaxUtilization3wks
    set timestamp =''
    truncate table tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    --load to table to be joined to Node feature class
    insert into tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    (Node, TwoWeeksAgo, PreviousWeek, CurrentWeek)
    select * from tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
    --calculate average utilization for all values in each record
    update tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    set average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0))/3
    from tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    Scott

    Issue is with variable @columnz.
    Scope of variables is only limited to the batch and if batch is over Variable is no more accessible.
    Reproduce Steps: 
    DECLARE @columnz int = 0
    Go --Scope of @columnz ends here
    SELECT @columnz -- Ends up with error
    So you have to remove GO keyword. I have commented 2 of them in below:
    DROP TABLE tmpNCPCNCDownstreamMaxUtilization3wks
    SELECT node
    ,max(utilization) AS max_Utilization
    ,DATE
    INTO tmpNCPCNCDownstreamMaxUtilization3wks
    FROM stage_ncpcncdownstream_temporal
    WHERE DATE BETWEEN DATEADD(day, - 20, GETDATE())
    AND GETDATE()
    GROUP BY node
    ,DATE
    ORDER BY node
    GO
    ALTER TABLE tmpNCPCNCDownstreamMaxUtilization3wks ADD TIMESTAMP VARCHAR(50)
    GO
    UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
    SET TIMESTAMP = 'WeekOf_' + cast(left(DATE, 11) AS VARCHAR)
    GO
    --drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
    --go
    DECLARE @columnz VARCHAR(8000)
    --GO
    SELECT @columnz = COALESCE(@columnz + ',[' + TIMESTAMP + ']', '[' + TIMESTAMP + ']')
    FROM tmpNCPCNCDownstreamMaxUtilization3wks
    GROUP BY TIMESTAMP
    ORDER BY TIMESTAMP
    --GO
    --pivot contents in @columns
    DECLARE @query VARCHAR(8000)
    SET @query = 'select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
    (select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
    pivot
    sum(max_Utilization) for timestamp in(' + @columnz + ')
    )as p'
    EXECUTE (@query)
    --empty contents from NCPCNCDownstreamMaxUtilization3wks
    UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
    SET TIMESTAMP = ''
    TRUNCATE TABLE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    --load to table to be joined to Node feature class
    INSERT INTO tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week (
    Node
    ,TwoWeeksAgo
    ,PreviousWeek
    ,CurrentWeek
    SELECT *
    FROM tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
    --calculate average utilization for all values in each record
    UPDATE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    SET average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0)) / 3
    FROM tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
    -Vaibhav Chaudhari

  • Execute SQL task for Email ToLine using COALESCE and two variables

    Hello...
    I am converting an old DTS package to SSIS. The old package consist of mostly ActiveX Script so I am breaking it down into steps. Basically... I am retreving a set of records that need to be sent via email to multiple people.  In my package to create
    my ToLine for the Send Mail Task I am using several steps. Frist I am using:
    SELECT CASE
              WHEN EXISTS (  SELECT        users.User_EmailAddress
    FROM            dbo.Errors INNER JOIN
                             dbo.Users ON users.user_id = Errors.MonitorAuditor_User_Id
    WHERE        ([Audit_Id] = ?) AND ([ErrorCode_Id] = ?) ) THEN
                 1
              ELSE
                 0
           END AS ValidEventID
    I use this to see if there is any records to create my email string. This works fine.  After this I have a Script Task that splits my pipe in two. When no records exist (User::ValidEventID == 0) I am loging that event to a log. When records do exist
    I am using another Execute SQL task to create the actual ToLine:
    Declare @combinedString VARCHAR(max)
    SELECT      @combinedString = COALESCE(@combinedString + ', ', '') + Users.User_EmailAddress
    FROM            dbo.Errors INNER JOIN
                             dbo.Users ON users.user_id = Errors.MonitorAuditor_User_Id
    WHERE        ([Audit_Id] = ?) AND ([ErrorCode_Id] = ?)
    SELECT convert(varchar(4000),@combinedString) as StringValue
    I have my resultSet set to Single Row. I have two variables coming if for the Audit_Id and ErrorCode_Id. My Result Set is set to a Variable: User::EmailAddressString.
    Next it goes through a foreach loop to map to the ToLine email variable that I created named User:User_EmailAddress.
    Then I am using that in my Send Email Task.
    It all works fine when I hard code my variables into the COALESCE statement but as soon as I replace that with the ? that SSIS requires for variables I am getting the following error:
    [Execute SQL Task] Error: Executing the query "Declare @combinedString VARCHAR(max)
    SELECT      ..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly,
    parameters not set correctly, or connection not established correctly.
    I have tried changing my resultset property, I have checked my paramenters and my connection. I don't understand why it works fine when I have my varaiables hard coded but not when I change them to the ?.
    Thanks in advance for you help in this matter.
    Reach for the unknown!

    Katherine... that did not work. 
    What I ended up doing was taking out the forloop all together. In my Execute SQL Task I changed the result set from single row to XML. I took out the  COALESCE statement and just went for something more basic:
    select users.User_EmailAddress + ';' as User_EmailAddress from Errors inner join users on users.user_id = Errors.MonitorAuditor_User_Id WHERE ([Audit_Id]  = ? AND [ErrorCode_Id] = ?)
    Currently I am just logging the string to a text file so I can see the results. In my text file the string is surrounded by <ROOT></ROOT>. So I will next I will work on triming that off the string and then populate my Send Mail Task.
    This is how I trimed off the <ROOT></ROOT>:
    Dts.Variables(
    "EmailAddressString").Value = Replace(Dts.Variables("EmailAddressString").Value,
    "<ROOT>",
    Dts.Variables(
    "EmailAddressString").Value = Replace(Dts.Variables("EmailAddressString").Value,
    ";</ROOT>",
    Thanks again everyone for the help!
    Reach for the unknown!

  • SSIS custom execute sql task : Failed with error

    I am developing a custom SSIS task for running sql task. But it fails with error - I'm trying to set the resultsetbinding to be used by next task in workflow.
    Error: 0xC0014054 at CustomSSISTask: Failed to lock variable "User::id" for read access with error 0xC0010001 "The variable cannot be found. This occurs when an attempt is made to retrieve a variable from the Variables collection on a container
    during execution of the package, and the variable is not there. The variable name may have changed or the variable is not being created.".
    Error: 0xC002F210 at CustomSSISTask, Execute SQL Task: Executing the query "SELECT id FROM sysobjects WHERE name = 'sysrowsets..." failed with the following error: "Failed to lock variable "User::id" for read access with error 0xC0010001
    "The variable cannot be found. This occurs when an attempt is made to retrieve a variable from the Variables collection on a container during execution of the package, and the variable is not there. The variable name may have changed or the variable is
    not being created.".
    ". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
    Warning: 0x80019002 at CustomSSISTask: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.  The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches
    the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
    Task failed: CustomSSISTask
    Here is the code sample I'm trying , 
            public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser,
                                                  IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
                MessageBox.Show("testing:");
                try
                    // Add the SQL Task
                    Package package = new Package();
                    package.Executables.Add("STOCK:SQLTask");
                    Microsoft.SqlServer.Dts.Runtime.Variable variable = package.Variables.Add("id", false, "User", 0);
                     // Get the task host wrapper
                    TaskHost taskHost = package.Executables[0] as TaskHost;
                    // Get the task object
                    ExecuteSQLTask task = taskHost.InnerObject as ExecuteSQLTask;
                    // Set core properties
                    task.Connection = connections[0].Name;
                    task.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'";
                    //task.SqlStatementSource =
                    //    "SELECT PersonID from [AmalgaSpeedTableData].[SpeedTable].[DimPerson] where PersonIntID  = '1'";
                    task.SqlStatementSourceType = SqlStatementSourceType.DirectInput;
                    // Add result set binding, map the id column to variable
                    IDTSResultBinding resultBinding = task.ResultSetBindings.Add();
                    //IDTSResultBinding resultBinding = task.ResultSetBindings.GetBinding(0);
                    resultBinding.ResultName = "variable";
                    resultBinding.DtsVariableName = variable.QualifiedName; //"User::id";
                    task.Execute(connections, variableDispenser, componentEvents, log, transaction);
                catch (Exception ex)
                    throw new ArgumentException(ex.Message);
                return DTSExecResult.Success;
    It doesnt throw any exception but custom task fails.
    Later I will be also using parametersetbindings to pass some input parameters to this task , since I'm stuck for out param - blocked moving ahead.
    Any help would be greatly appreciated.
    Thanks
    Sang

    Hi, could you check whether the following threads help:
    http://stackoverflow.com/questions/5787621/ssis-package-failed-to-locak-variable-for-read-access-with-error-0xc0010001
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/40ee7eff-5ec1-426f-a1a8-ab85b40b51aa/error-variable-can-not-be-found-while-executing-package-from-the-net-code?forum=sqlintegrationservices
    Regards, Leo

  • Execute SQl Task Error SSIS Package

    Hi all,
    I`m using for each loop container in my package to grab the file name from the source path. I have created 2 vairables
    FilePath and SourceFolder
    I`m using execute sql task inside the container and this is my query
    Insert into [dbo].[DCA_FF_TEST] (File_Name,File_Date) SELECT File_name = ?,
    File_Date = GetDate()
    Please not the Table I am trying to insert has more columns but at this stage I dont need them.
    When i execute the task I get an error
    [Execute SQL Task] Error: Executing the query "
    INSERT INTO   [dbo].[DCA_FF_TEST] ([File_Name],[F..." failed with the following error: "The statement has been terminated.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters
    not set correctly, or connection not established correctly.
    Can someone point me in the right direction? Am I missing anything?
    Resultset property Set to None
    Parameter Mapping: Variablename: FilePath , Direction: Input, datatype : Varchar, Parametername: 0, ParameterSize: 100.
    I`ve checked the connection as well it works.
    FM

    Did you try
    Insert into  [dbo].[DCA_FF_TEST] (File_Name,File_Date)
    SELECT ?, GetDate()
    Or
    Insert into  [dbo].[DCA_FF_TEST] (File_Name,File_Date) VALUES (?, GetDate())
    A Fan of SSIS, SSRS and SSAS

  • Customized Execute SQL Task in SSIS

    Hi,
    I,m using Execute SQL Task in SSIS Package with these configuration ..
    But, If SQL Statement doesn't report any record mean Query is not returning any data then this Task will be failed.
    How can I assure that If there is no record is returning in query that " Execute SQL Task " should bot be executed .
    Also I If I can do the same thing through other methods in SSIS, Pls response .
    -Ashish

    Hi Ashish,
    The Execute SQL Task failed because you had set the ResultSet to “Single row”, however, the SQLStatement didn’t return any records. If you don’t want to execute this task when the query doesn’t return any records, you can use the following method:
    Create a String type variable RowCnt, add another Execute SQL Task prior to this task.
    In the new Execute SQL Task, input the SQLStatement as “Select Count(*) From Table”, set the ResultSet to “Single row”, and map the result set 0 to the variable RowCnt.
    Join the two tasks (green line), and edit the Precedence Constraint (Green line), and set the expression to “(DT_I4)@[User::RowCnt]>0”.
    Regards,
    Mike Yin
    TechNet Community Support

  • How to use a parameter in an Execute SQL Tasks in SSDT executed against Netezza

    Good Evening,
    How can I pass a parameter in an Execute SQL Tasks in SSDT executed against Netezza?  Below are my settings and error message.
    [Execute SQL Task] Error: Executing the query ""TRUNCATE TABLE" ?"_POC..JOHN_TEST"" failed with the following error: "Syntax error or access violation". Possible failure reasons: Problems with the query, "ResultSet"
    property not set correctly, parameters not set correctly, or connection not established correctly.
    Thank you in advance for your assistance.
    Brett

    Hi Baloun,
    Based on my further research, just as you said, we cannot directly use table name as a variable.
    To fix this issue, we can change the SQL command in the SQLStatement property as below:
    declare @sql varchar(100)
    set @sql = 'TRUNCATE TABLE ' + ? +'_POC..JOHN_TEST'
    exec(@sql)
    go
    The Parameter Mapping pane use the former settings in your picture.
    Reference:
    http://www.bidn.com/blogs/kylewalker/ssis/2063/parameters-don-t-always-work-in-your-execute-sql-task
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • HELP: SSIS 2012 - Execute SQL Task with resultset to populate user variables produces DBNull error

    I am experiencing an unexplainable behavior with the Execute SQL Task control in SSIS 2012. The following is a description of how to simulate
    the issue I will attempt to describe:
    1. Create a package and add two variables User::varTest1 and User::varTest2 both of String type with default value of "Select GetDate()"
    for each, have shown this to not matter as the same behavior occurs when using a fixed string value or empty string value.
    2. Add a new Execute SQL Task to the control flow.
    3. Configure an OLE DB connection.
    4. Set SQLSourceType = "Direct Input"
    5. Set the ResultSet property of the task to "Single Row"
    6. In the ResultSet tab add two results as follows: 
    Result Name: returnvalue1, Variable Name: User::varTest1
    Result Name: returnvalue2, Variable Name: User::varTest2
    7. Set an expression for the SqlStatementSource property with a string value of "Select 'Test' returnvalue1, 'Testing' returnvalue2'"
    The idea is that the source would be dynamically set in order to run a t-sql statement which would have dynamic values for database name
    or object that would be created at runtime and then executed to set the user variable values from its resultset. Instead what occurs is that a DBNull error occurs.
    I am not sure if anyone else has experienced this behavior performing similiar actions with the Execute SQL Task or not. Any help would be
    appreciated. The exact message is as follows:
    [Execute SQL Task] Error: An error occurred while assigning a value to variable "varRestoreScript": "The type of the value
    (DBNull) being assigned to variable "User::varRestoreScript" differs from the current variable type (String). Variables may not change type during execution. Variable types are strict, except for variables of type Object.
    User::varRestoreScript is the first return value. And even with the a dummy select the same result occurs. I have narrowed the issue down
    to the T-SQL Statement structure itself. 
    The following works just fine within the execute sql task control as long as no resultset is configured for return:
    "Declare @dynamicSQL nvarchar(max)
    Select @dynamicSQL = name 
    From sys.databases 
    Where name = 'master'
    Select atest_var1=@dynamicSQL, atest_var2='static'"
    I have tried various iterations of the script above with no success. However, if I use the following derivative of it the task completes
    successfully and variables are set as expected.  This will not work for my scenario however as I need to dynamically build a string spanning multiple resultsets to build one of the variable values.
    "Select atest_var1=name, atest_var2='static'
    From sys.databases
    Where name = 'master'
    I have a sample package which can reproduce this issue using the above code.  You can get to that through the post on www.sqlservercentral.com/Forums/Topic1582670-364-1.aspx
    Scott

    Arthur,  the query when executed doesn't return a null value for the @dynamicSQL variable.  It returns "master" as a string value.  Even the following fails which implements that suggestion:
    Declare @dynamicSQL as nvarchar(max)
    Select @dynamicSQL = name
    From master.sys.databases 
    Where name = 'master' -- (or any other DB name)
    I believe I have found the cause of the issue.  It is datatype and size related.  The above script will properly set the variables in the resultset as long as you don't use nvarchar(max) or varchar(max).  This makes the maximum data size for
    a String variable 4000 characters whether unicode or non-unicode typed.

  • Multiple Select statements in EXECUTE SQL TASK in SSIS

    Can we write multiple select statements in execute sql task(SSIS).
    If possible how to assign them to variables in result statement

    Hi ,
    You can use below steps to set result set to variable.
    1.In the Execute SQL Task Editor dialog box, on the General page, select the Single row, Full result set, or XML result set type(According to your result set).
    2.Click Result Set.
    3.To add a result set mapping, click Add.
    4.From the Variables Name list, select a variable or create a new variable.
    What is multiple selection ? May be below can be used in your scenario !
    http://stackoverflow.com/questions/17698908/how-to-set-multiple-ssis-variables-in-sql-task
    What you want to achieve ?
    Thanks
    Please Mark This As Answer or vote for Helpful Post if this helps you to solve your question/problem. http://techequation.com

  • Send Email using Execute SQL Task??????

    I need to send the bad records in the data flow.  I am attempting to do this using Execute SQL Tasks.  Please give me steps I need to accomplish this.  I have not set any variables up yet, assuming I need too.

    Just add a Send mail Task (or Script Task if using gmail etc which requires authentication) and pass the file as an attachment. Make sure you've a step (Script Task) to check if file length > 0 (ie file has records) before you link it to Send mail Task
    ie use a conditional precedence constraint (Expression And Constraint option)
    See these links for more details
    http://dwteam.in/send-mail-in-ssis-using-gmail/
    http://www.mssqltips.com/sqlservertip/1753/sending-html-formatted-email-in-sql-server-using-the-ssis-script-task/
    https://www.simple-talk.com/sql/ssis/working-with-precedence-constraints-in-sql-server-integration-services/
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • SSIS Package Load Failure and is missing Execute SQL Task in Toolbox

    Also, BIDS closes after right-clicking the toolbox and selecting “Choose Items”.
    I’ve tried several ways to fix these issues with no success.
    I’m running SSIS/SSMS/SQL Server 2008 R2 (but not running an SQL instance on my PC) on a Windows XP with Service Pack 3 workstation. I get the following errors:
    WHEN OPENING BIDS:
    I get 2 errors titled “Package Load Failure”. They both reference ‘Visual Studio Explorers and Designers Package’ as being what failed to load. The first message references GUID 8D8529D3-625D-4496-8354-3DAD630ECC1B. The second references GUID AA612177-A69A-4391-B2F4-17F8A88F4BBA
    . They both mention contacting the package vendor, but I haven’t got any Add-ins loaded so I’m not sure what that means exactly. They also both ask if I’d like to skip loading the package in the future.
    ONCE BIDS IS OPEN:
    No error messages appear here. There is no ‘Execute SQL Task’ in the toolbox for Control Flows. Also, if I attempt to open a project containing this object (Execute SQL Task), I get this error in a modal window:
    TITLE: Microsoft Visual Studio
    There were errors while the package was being loaded.
    The package might be corrupted.
    See the Error List for details.
    BUTTONS:
    OK
    . . . and these errors in the Error List at the bottom of the IDE:
    Error      1             
    Error loading Package.dtsx: Failed to load task "Execute SQL Task", type "Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask.ExecuteSQLTask, Microsoft.SqlServer.SQLTask, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91". The contact information
    for this task is "Execute SQL Task; Microsoft Corporation; Microsoft SQL Server 2008 R2; © 2007 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1". 
            C:\Documents and Settings\848862.VCHS_NT_DOMAIN\My Documents\Visual Studio 2008\Projects\LearnSSIS\LearnSSIS\Package.dtsx   
    1               
    1             
    Error      2             
    Validation error. Execute SQL Task : The task has failed to load. The contact information for this task is "Execute SQL Task; Microsoft Corporation; Microsoft SQL Server 2008 R2; © 2007 Microsoft Corporation; All Rights Reserved;http://www.microsoft.com/sql/support/default.asp;1". 
            Package.dtsx    
    0             
    0             
    Error      3             
    Validation error. Execute SQL Task : There were errors during task validation. 
       Package.dtsx    
    0             
    0               
    Finally, when I attempt to add the Execute SQL Task via the Tools menu, “Choose Toolbox Items” selection, I do get the tabbed box for adding things. However, they only come up after issuing this error:
    The following assemblies are installed SDK assemblies but could not be shown in the customize toolbox dialog because they are missing one or more components. Please make sure that all necessary libraries are available:
    Microsoft.SqlServer.SqlCEDest.dll
    Microsoft.SqlServer.Management.CollectorTasks.dll
    Microsoft.SqlServer.SQLTask.dll
    System.Data.SqlServerCe.dll
    Microsoft.Synchronization.Data.SqlServerCe.dll
    (above dll repeated at bottom of message)
    After this message, I have my choice of .NET Framework Compnents. When I select COM Components, those come up with no problem. The WPF Components tab generates the same dll error above. The Maintenance tab is empty. The SSIS Data Flow Items tab loads fine,
    as does the SSIS Control Flow Items tab – but there’s no Execute SQL Task there either.
    If you open the toolbox (on a new project, with a project loaded, or without a project loaded) and right-click, then select “Choose Items”, the entire application quickly closes. This “closing behavior” is the same thing you get if you attempt to add toolbox
    items through either the Tools menu or the right-click method when you launch BIDS in SafeMode.
    In an effort to fix this – I’ve rolled back the .NET Framework version to 3.0 and reinstalled back up to 4; I’ve uninstalled and reinstalled SQL Server 2008 R2 shared services as well as the entire application; I’ve cleared the .tbd files from my user profile;
    and I’ve run several things from the command line (devenv.exe /resetuserdata, /setup, /resetskippkgs, etc.). Lastly – I’ve applied every Service Pack and update applicable to my PC (ok, it belongs to my employer – but no one here has been able to figure this
    out either).
    After having worked this for several days now and, I think, exhausting every available avenue from search engines – I turn to you. Please let me know if you can help. Also, I can provide any additional
    files or information you may require.
    CBS

    try: Devenv.exe /ResetSettings
    http://msdn.microsoft.com/en-us/library/ms241273(v=vs.80).aspx
    Or try this (it's for 2005, but maybe it works for 2008 aswell):
    http://geekswithblogs.net/cicorias/archive/2007/10/10/Restoring-Missing-Toolbox-Items-in-Visual-Studio-2005---just.aspx
    or try
    http://stackoverflow.com/questions/1268298/how-to-rebuild-the-visual-studio-toolbox
    "You can also go into the folder "C:\Documents and Settings\\Local Settings\Application Data\Microsoft\VisualStudio\9.0" and delete the *.tbd files.  I have had to do this a couple times to get rid of duplicate items and when Reset Toolbox crashes
    without warning"
    Please mark the post as answered if it answers your question | My SSIS Blog:
    http://microsoft-ssis.blogspot.com |
    Twitter

  • Using Union in Execute SQL Task

    I am using the following SQL statement in an Excute SQL Task:
    declare @RespAreaSubAreaID int, @UserLevelID int, @SubmittedByUserID int, @RespAreaID int, @SubAreaID int
    Set @RespAreaSubAreaID = ?
    Set @SubmittedByUserID = ?
    Set @UserLevelID = ?
    set @RespAreaID = ?
    set @SubAreaID = ?
    select users.User_EmailAddress + ';' As CC
    from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
    where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 4 and users.user_id <> @SubmittedByUserID)
    union
    select users.User_EmailAddress + ',' As CC
    from users inner join UserLevelsNotificationFrequencys on users.user_Id = UserLevelsNotificationFrequencys.User_id
    where UserLevelID = @UserLevelID and RespAreaSubAreaID = @RespAreaSubAreaID and (NotificationFrequencyID = 1)
     I have my parameter mapped correctly. My results set is set to xml because I want it all in one string to use as a variable named User:CC. On the Result Set tab the result name is 0 and the variable name is User:CC. When I run my package I am getting
    the error below. Can I not do a union query in the execute SQL task? I tried to not declare anything and just map to each of the variables that I am passing in the order that they are needed but that didn't work either. Thanks in advance for your help in this
    matter.
     [Execute SQL Task] Error: Executing the query "declare @RespAreaSubAreaID int, @NotificationID
    in..." failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection
    not established correctly.
    Reach for the unknown!

    Thank you for your reply but I am not using the Data Flow. All my work is happening on the Control Flow. I am looping through a set of records and emailing them to the correct
    people. Setting my result set to XML worked for the To Line (See my earlier post Execute SQL task for Email ToLine using COALESCE and two variables) and now I am working on the CC line which is more complicated because it uses a union statement.
    Reach for the unknown!

Maybe you are looking for

  • Can I password protect my numbers spreadsheet on my iPad

    I just purchased my first apple ipad2 and I do a lot of spreadsheets in excel, I bought numbers and need to password protect my file so other family members can not get to my files. Can this be done? If so, how? Best regards, John

  • How can I receive the value of a selected item in the backing bean

    I have a table in a jspx file. When I go to the detail page I want to do something with the value of the currentrow. I want do a calculaction of the value of ClbId. How can I receive the value of the selected ClbId in my backing bean <af:table value=

  • TS5183 My mic in speker phone and Siri dasen"t work  in i phone 5

    Hi plz i have a problem withe speakerphone mic not work and in Siri mic not work plz help  me 

  • External editors and file types

    Hi, I have just started using Aperture, so far very pleased but have some questions so thought I would ask the experts. 1. I have selected Elements 10 as an external editor, when I select to edit aperture creates a PSD file and starts Element 10 but

  • OIM Delegation

    Hi! I`m trying to configure approval process in OIM, and as a part of this process there is a need to use delegation feature. BUT: after delegate makes a decision request has to be returned to person, who delegated this request. By default after dele