需要通配符XML节点值方法

时间:2015-10-23 15:31:03

标签: sql xml ssis

解析SSIS包以用于文档目的,并且我想为脚本代码添加通配符,以防创建者没有将名称保留为" ScriptMain"

以下是我现在的代码部分:

    SELECT RowID as ControlFlowRowID,
    CF.TaskName
    ,cfnodes1.x.value('./ProjectItem[@Name=''ScriptMain.cs''] [1]', 'nvarchar(max)') CSScript
    ,cfnodes1.x.value('./ProjectItem[@Name=''ScriptMain.vb''][1]', 'nvarchar(max)') VBScript
FROM ##tmp_SSISpkgControlFlow cf
CROSS APPLY Cf.ScriptTaskQry.nodes('.') AS cfnodes1(x)

我想要取消对ScriptMain的依赖。任何帮助都会很棒。

有问题的XML部分:

</ProjectItem>
              <ProjectItem
                Name="ScriptMain.cs"
                Encoding="UTF8"><![CDATA[#region Help:  Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
 * a .Net application within the context of an Integration Services control flow. 
 * 
 * Expand the other regions which have "Help" prefixes for examples of specific ways to use
 * Integration Services features within this script task. */
#endregion


#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.IO;

#endregion

namespace ST_2817a78c2b684bfc87bfd7fb00086a37
{
    /// <summary>
    /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    /// or parent of this class.
    /// </summary>
    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */

        #endregion

        #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion

        #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion


        /// <summary>
        /// This method is called when this script task executes in the control flow.
        /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        /// To open Help, press F1.
        /// </summary>
        public void Main()
        {


            string connectionString = "";
            string filepath = Dts.Variables["varSourceFilePath"].Value.ToString();
            string serverName = Dts.Variables["varServerName"].Value.ToString();
            string databaseName = Dts.Variables["varDBName"].Value.ToString();


            connectionString = @"Data Source=" + serverName + ";Initial Catalog=" + databaseName + ";Integrated Security=true;";

            StreamReader reader = File.OpenText(filepath);
            string input = null;
            string abc = null;
            string Col;
            while ((input = reader.ReadLine()) != null)
            {
                abc = abc + input;
            }
            Col = abc.ToString();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string queryString = "insert into [pkgStats]([PackageXML]) Values(@field1)";
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Parameters.AddWithValue("@field1", Col.ToString());

                command.ExecuteReader();
                connection.Close();
            }

            Dts.TaskResult = (int)ScriptResults.Success;
        }

        #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

    }
}]]></ProjectItem>
              <ProjectItem
                Name="ST_2817a78c2b684bfc87bfd7fb00086a37.csproj"
                Encoding="UTF8"><![CDATA[<?xml version="1.0" encoding="utf-8"?>

更新:这是修改后的SQL,其中应用了接受的答案:

    select 
    Data.ControlFlowRowID as CF_Rowid,
    ScriptName,
    ScriptCode as ScriptText,
    ScriptType

from
(
    SELECT RowID as ControlFlowRowID,
        CF.TaskName,
        CASE WHEN ProjectItem.value('@Name','varchar(max)') LIKE '%.vb' THEN 'VB Script' 
            WHEN ProjectItem.value('@Name','varchar(max)') LIKE '%.cs' THEN 'C# SCript'
            ELSE 'Other'
       END AS ScriptType
      ,ProjectItem.value('@Name','varchar(max)') AS ScriptName
      ,ProjectItem.value('.','varchar(max)') AS ScriptCode
            FROM ##tmp_SSISpkgControlFlow cf
                CROSS APPLY Cf.ScriptTaskQry.nodes('//ProjectItem') AS A(ProjectItem)

) as Data
where Data.ScriptCode is not null and ScriptType <> 'Other'

1 个答案:

答案 0 :(得分:1)

抱歉延迟......

你正在寻找这样的东西吗?

(只需将其粘贴到一个空的查询窗口中并根据您的需求进行调整)

DECLARE @xml XML=
'<Root>
    <ProjectItem Name="ScriptMain.cs" Encoding="UTF8">
        <![CDATA[Here you find CS code]]>
    </ProjectItem>
    <ProjectItem Name="ScriptMain.vb" Encoding="UTF8">
        <![CDATA[Here you find Vb code]]>
    </ProjectItem>
    <ProjectItem Name="OtherName.cs" Encoding="UTF8">
        <![CDATA[Here you find CS code with other name]]>
    </ProjectItem>
    <ProjectItem Name="OtherName.vb" Encoding="UTF8">
        <![CDATA[Here you find VB code with other name]]>
    </ProjectItem>
    <ProjectItem Name="OtherName.xy" Encoding="UTF8">
        <![CDATA[Here you find XY code with other name]]>
    </ProjectItem>
</Root>
'
;
select CASE WHEN ProjectItem.value('@Name','varchar(max)') LIKE '%.vb' THEN 'VB' 
            WHEN ProjectItem.value('@Name','varchar(max)') LIKE '%.cs' THEN 'CS'
            ELSE 'Other'
       END AS ScriptType
      ,ProjectItem.value('@Name','varchar(max)') AS ScriptName
      ,ProjectItem.value('.','varchar(max)') AS ScriptCode
FROM @xml.nodes('//ProjectItem') AS A(ProjectItem)

结果

ScriptType  ScriptName     ScriptCode
   CS       ScriptMain.cs  Here you find CS code
   VB       ScriptMain.vb  Here you find Vb code
   CS       OtherName.cs   Here you find CS code with other name
   VB       OtherName.vb   Here you find VB code with other name
 Other      OtherName.xy   Here you find XY code with other name