Execute SQL Task - FOR XML PATH query error

I have the following query
SELECT pl.Id,
pl.StartTime,
pl.EndTime,
pl.PackageName,
pl.Computer,
pl.Operator,
CASE WHEN (CHARINDEX('stack trace', pl.ErrorDescription) > 0) Then
    SUBSTRING(pl.ErrorDescription, 0, CHARINDEX('stack trace', pl.ErrorDescription))
    ELSE
    pl.ErrorDescription
    END as ErrorDescription
ISNULL(ErrorFile,'') as ErrorFile,
'Not Applicable' as SourceSystem
FROM etl.PackageLog as pl
WHERE pl.Processed = 0
ORDER BY pl.StartTime, pl.PackageName
FOR XML PATH('Row'), ROOT(N'FieldingCounts')
in a Execute SQL Task and i get the following error:
[Execute SQL Task] Error: Executing the query "SELECT pl.Id,
pl.StartTime,
pl.EndTime,
pl.Package..." failed with the following error: "An invalid character was found in text content.
". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
The query execute without problem in database and in the ssis package doens't run because of the column
CASE WHEN (CHARINDEX('stack trace', pl.ErrorDescription) > 0) Then
    SUBSTRING(pl.ErrorDescription, 0, CHARINDEX('stack trace', pl.ErrorDescription))
    ELSE
    pl.ErrorDescription
    END as ErrorDescription
Any help to overcome the problem?
Thanks

Hi,
It looks like that you must be trying to set the result of the query to some variable from the Execute SQL Task. If yes, make sure that the target variable is of the correct data type where XML string  can fit into. Considering that in SSIS, we have
some limit for XML strings.
Please let me know if it doesn't help.
Thanks,
Nimit

Similar Messages

  • 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!

  • 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!

  • [Execute SQL Task] Error: Executing the query failed with error: "The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION."

    I have an package with source , data flow and destination to execute on begin and commit.
    in the below i have just used for questioning purpose with diagram removing my Data Flow task explaining my problem
    on execution, i get error as
    [Execute SQL Task] Error: Executing the query "COMMIT TRAN DimCompanyCode" failed with the following error: "The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.". Possible failure reasons: Problems with the query, "ResultSet"
    property not set correctly, parameters not set correctly, or connection not established correctly.
    as mentioned , i have checked the ResultSet, parameters , connection establish.. all are fine.
    Kindly advice on what has to be done.
    ShanmugaRaj

    To avoid this error, the RetainSameConnection property should set to 'True' for the Connection Manager - Application_DB.
    Narsimha

  • [Execute SQL Task] Error: Executing the query "DECLARE_@XMLA nvarchar(3000) ,__@DateSerial nvarch..." failed with the following error: "Incorrect syntax near '-'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly,

    Hi
    DECLARE @XMLA nvarchar(3000)
    , @DateSerial nvarchar(35);
    -- Change date to format YYYYMMDDHHMMSS
    SET @DateSerial = CAST(GETDATE() AS DATE);
    --SELECT @DateSerial
    Set @XMLA = 
    N' <Batch xmlns="http://schemas.microsoft.com/analysis services/2003/engine">
     <ErrorConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2"
    xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200"
    xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200">
    <KeyErrorLimit>-1</KeyErrorLimit>
    <KeyNotFound>IgnoreError</KeyNotFound>
    <NullKeyNotAllowed>IgnoreError</NullKeyNotAllowed>
     </ErrorConfiguration>
     <Parallel>
    <Process xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2"
    xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200"
    xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300" xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300">
     <Object>
     <DatabaseID>MultidimensionalProject5</DatabaseID>
     <CubeID>giri</CubeID>
     <MeasureGroupID>Fact Internet Sales</MeasureGroupID>
     </Object>
     <Type>ProcessFull</Type>
     <WriteBackTableCreation>UseExisting</WriteBackTableCreation>
     </Process>
      </Parallel>
    </Batch>';
    EXEC (@XMLA) At SHALL-PCAdventureWorksDw ;
     iam executive the    query when iam getting below error.
      [Execute SQL Task] Error: Executing the query "DECLARE
    @XMLA nvarchar(3000)
    , @DateSerial nvarch..." failed with the following error: "Incorrect syntax near '-'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set
    correctly, or connection not established correctly. 
     how to solve this error;
     please help me

    What are you trying to do? What sort of data source is  SHALL-PCAdventureWorksDw?
    When you use EXEC() AT, I would execpt to see an SQL string to be passed to EXEC(), but you are passing an XML string????
    If you explain why you think this would work in the first place, maybe we can help you.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Execute SQL Task Editor: The query failed to parse. Syntax error, permission violation, or other nonspecific error.

    Environment: SQL Server 2008 R2
    Code:
    CREATE TABLE dbo.PkgAudit
    PkgAuditID INT IDENTITY(1, 1),
    PackageName VARCHAR(100),
    LoadTime DATETIME ,
    NumberofRecords VARCHAR(50),
    Status1 VARCHAR(50),
    Status2 VARCHAR(50),
    The following code is inserted in the SQL Task Execute Editor
    INSERT INTO dbo.PkgAudit(PackageName
    ,LoadTime
    ,NumberofRecords
    ,Status1
    ,Status2
    ) VALUES(?,?,?,?,?)
    Screen Shot (Parameter Mapping):
    Problem: an error Message occurred when I hit Parse Query Button in the Execute SQL Task Editor, "Execute SQL: Task Editor: The query failed to parse. Syntax error, permission violation, or other nonspecific error". How I could Solve this
    problem  

    Different connection providers require different Parameter syntax. E.g. ADO @ParameterName notatoin, not just an offset of 0,1 etc.
    Arthur My Blog

  • 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

  • Execute SQL Task fails when specific column names are mentioned in Excel Query

    Hi,
    I have a requirement for extracting Excel data with thespecific column order. So instead of using the below query,
    Select * From [Sheet1$A1:ZZ1]
    I use the below one,
    Select col1,
    col2,
    col91
    From [CRM$A1:ZZ1]
    So I have totally 91 columns.
    I don't face any issues when i use the before query. i.e. direct select * from sheet1
    But when i specify column names and do a select from the sheet it throws error as below,
    [Execute SQL Task] Error: Executing the query "Select
    [Col1] 
    From [Sheet1$..." failed with the following error: "No value given for one or more required parameters.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not
    set correctly, or connection not established correctly.
    I just need to retrieve the column name alone and not any of the values to it. So when i do simple select * it gives the column names in the order of what it is been with the excel. But i do want it to be sorted in alphabetically and to retrieve the column
    names. 
    I am not getting any proper solution for this for past 1 and a half days. May anyone of you please help me get it sorted? - Thank you!
    --------------------------- Radhai Krish | Golden Age is no more far | --------------------------

    Please use something like below:
    SELECT F1 AS Col1, F2 AS Col2, F3 AS Col3, ...
    FROM [Sheet1$A1:ZZ1]
    Cheers,
    Vaibhav Chaudhari
    [MCTS],
    [MCP]

  • 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

  • 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

  • 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.

  • Execute SQL Task Error

    I am using the following query in Execute SQL Task
    SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETAILS
    WHERE source_filename = ?
    AND lTRIM(RTRIM([BILLING DATE])) <> '') WHEN 0 THEN (SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD])
    ELSE
    (SELECT TOP 1 [BILLING DATE] FROM STG_APJ_APIW_DETAILS
    WHERE source_filename = ?
    AND lTRIM(RTRIM([BILLING DATE])) <> '')
    END
    In parameter Mapping i have created two parameters and in result set i choose my variable.
    Result set property is Single Row.
    Following is the error message i received,
    [Execute SQL Task] Error: Executing the query "SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETA..." 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.
    Sarvan

    I cant see where you've named resultset. try like below to make sure resultset has the name used in resultset tab
    SELECT CASE(SELECT COUNT(*) FROM STG_APJ_APIW_DETAILS
    WHERE source_filename = ?
    AND lTRIM(RTRIM([BILLING DATE])) <> '') WHEN 0 THEN (SELECT CONVERT(VARCHAR(8), GETDATE(), 112))
    ELSE
    (SELECT TOP 1 [BILLING DATE] FROM STG_APJ_APIW_DETAILS
    WHERE source_filename = ?
    AND lTRIM(RTRIM([BILLING DATE])) <> '')
    END AS [Billing Date]
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Biztalk WCF-SQL polling sample using a FOR XML Path

    I've been searching in the web for a sample that uses FOR XML "PATH" to poll the SQL database . The result returned from my query is a parent child data and FOR XML PATH is the best choice to structure it in that way . I guess I'm missing something while
    generating the schemas from this stored procedure.
    I guess Dan Rosanova has touched on this concept (http://social.technet.microsoft.com/wiki/contents/articles/3480.aspx)
    , but its using XML Auto. Again there is no sample available so makes things a bit difficult.
    Can someone point to a sample walkthrough , generating the schemas and then later using it in the application.
    Thanks
    Anthstone

    I used XMLPolling and it worked for me. you can go for XMLPolling. Steps to be followed:
    1) Create the SP which will have the SELECT query similar to below:
    ;WITH XMLNAMESPACES (default 'http://yourcustomnamespace')
     Select * from Employee FOR XML PATH('YourCustomRootNode') 
    2) Create a schema out of the table using the following query
    Select * from Employee for
    xml
    auto,
    xmlschema 
    3) Re-name the root name and namespace as per you mentioned in point#1 (YourCustomRootNode)
    4) Create an Envelope Schema and refer the schema from point#3. Also make a note of the root node name and namespace that we need to specify
    in the admin console.
    5) Assign the Body XPath to debatch. Refer
    this.  Deploy the solution.
    6) In the Admin console, add the Root Node Name and namespace mentioned in point#4 under "XmlStoredProcedureRoodNodeName" and "XmlStoredProcedureRoodNodeNamespace"
    There you go. I did this for debatching. You can do for nomarl batch message instead of Envelope create a normal document schema.
    Thanks
    SKGuru

  • Query regarding FOR XML PATH

    I have found a script that contains the following:
    stuff(
    select
    ', ' +
    fielda
    from
    tablea
    for
    xml path (''),
    type).value
    'nvarchar(max)')
    ,1,2,
    anotherfield
    This will concatenate field a and the stuff will remove the leading comma.
    I have amended the script to the following and it still works:
    Stuff(
    select
    ', ' +
    fielda
    from
    tablea
    for
    xml path (''))
    ,1,2,
     Afield,
    Please could somebody tell me why the following has been inserted after the
    for xml path ('')
    section
    type).value
    ('.', 'nvarchar(max)')

    Erland - I just did a quick test. The differences weren't as bad as the subtree estimates would have indicated but they weren't exactly close either. The typed version (on average) took just over twice as long to execute.
    Test conditions were as follows:
    AdventureWorks2012 database 
    On average, the non-typed version executed in ~190 ms and the typed version executes in ~405 ms.
    Test bed was the following:
    @@VERSION = 
    Microsoft SQL Server 2012 - 11.0.2218.0 (X64) 
    Jun 12 2012 13:05:25 
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
    Hardware = 
    Processor: Core i7-4770K @ 3.50GHz (4 physical cores / 8 logical cores)
    Ram: 16.0 GB @ 2400 MHz
    HD: SSD
    Here are the two test scripts that I used... (each run in it own SSMS tab)
    -- Typed version --
    DECLARE @BegDT DATETIME2(7) = SYSDATETIME()
    SELECT
    sod1.SalesOrderID,
    STUFF((
    SELECT ', ' + CAST(sod2.ProductID AS VARCHAR(8))
    FROM Sales.SalesOrderDetail sod2
    WHERE sod1.SalesOrderID = sod2.SalesOrderID
    FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 2, '') AS csv
    FROM
    Sales.SalesOrderDetail sod1
    GROUP BY
    sod1.SalesOrderID
    SELECT DATEDIFF(ms, @BegDT, SYSDATETIME()) AS ExecTimeMS
    -- Non-typed version --
    DECLARE @BegDT DATETIME2(7) = SYSDATETIME()
    SELECT
    sod1.SalesOrderID,
    STUFF((
    SELECT ', ' + CAST(sod2.ProductID AS VARCHAR(8))
    FROM Sales.SalesOrderDetail sod2
    WHERE sod1.SalesOrderID = sod2.SalesOrderID
    FOR XML PATH('')), 1, 2, '') AS csv
    FROM
    Sales.SalesOrderDetail sod1
    GROUP BY
    sod1.SalesOrderID
    SELECT DATEDIFF(ms, @BegDT, SYSDATETIME()) AS ExecTimeMS
    If you see holes in my test approach, please let me know.
    Thanks,
    Jason
    Jason Long

  • "for XML path "  Oracle equivalent of this SQL expression

    SELECT TheID,
    REPLACE(
    RTRIM(
    SELECT StudentID + ' '
    FROM StudentinSchoolLocation TL
    WHERE (LocationID = Results.LocationID)
    FOR XML PATH ('')
    ) AS StudentIDs,
    What is the equivalent of 'For XML path' used above
    The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common location
    Works perfectly in SQL.
    Thank you

    Hi,
    user6287828 wrote:
    The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common locationThat's called "String Aggregation"
    [AskTom.oracle.com|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] shows several different ways to do it.
    I recommend the first one, the user-defined function STRAGG, which you can copy from that page.
    On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
    WM_CONCAT is not documented, so you may not want to use it in your Production applications.
    STRAGG is not so convenient if the order of items in the concatenated string is important.
    In that case, use XMLAGG or SYS_CONNECT_BY_PATH, as shown later in the asktom page.
    MODEL can also do ordered string aggregation.

Maybe you are looking for

  • Two cost objects Sales order , OKB9 business area +order

    Hi All, While posting intercompany IR system thronging below error messageu2026 Enter only one true account assignment Message no. KI249 Diagnosis You made assignments to several objects in CO (cost center, order, project etc.). 2 of these have been

  • Server communications error in Sharepoint365/Access web app

    I'm having a similar issue to this post using Office365 (academic). I have an Access web app that was working fine until about 1 week ago when suddenly became very slow to start on a web browser, and then any changes I make in Access 2013 and then at

  • Macbook Pro speaker buzzing noise

    So while playing LoL today I noticed a soft buzzing/vibrating sound coming across my speakers, at first I thought nothing of it, but now that I'm back on it, it's worsened. Sound is now staticy and vibrated. Any ideas on how to fix, and do not tell m

  • Lion: "Mail quit unexpectedly" after 5-10 seconds

    My MacPro is set up to switch users.  For one user, mail works fine.  For the other user, 5-10 seconds after opening Mail, it disappears and I get the message "Mail quit unexpectedly."  I need suggestions as to how to get all my old mail back.  Thank

  • Zen micro Firmware placement (physical

    Okey, where in the Zen micro is the firmware stored?i want to know since i had a zen micro, but the hardri've died and it cant startup (weird hd noises)so i bought one with damaged jack-plug and switched the hardri've. thing is that the "new" one get