SSIS 平面文件存在 -- 当不存在文件时,脚本任务将失败



我在SQL Server 2008 R2下的SSIS(BIDS(工作。 我有一个将平面文件导入 OLE DB 的包。 在导入数据流任务之前,我有一个脚本任务(用 C# 而不是 VB 编写(来测试该文件是否存在。 我对脚本任务有 2 个优先约束。 第一个是我的成功路径(评估操作 ="约束"和值 ="成功"(,它转到数据流任务。 第二个是我的失败路径(评估操作 ="约束"和值 ="失败"(,它转到虚拟任务(SQL 任务(,以便在文件不存在时包不会失败。

在调试中,我确认,当文件存在时,它会一直执行数据流任务(如预期的那样(。 但是,当文件不存在时,包将失败;特别是,它在第一步(即脚本任务(失败。 我不知道我做错了什么。 下面是我的脚本任务代码:

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
namespace ST_2f8cf79f6fe0443b9c09c453433a0258.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion
        public void Main()
        {
            if (File.Exists(Dts.Variables["PRC_file_path"].Value.ToString()))
            {
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            else
            {
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
        }
    }
}

据我所知,它的行为完全符合预期; 如果文件不存在,则脚本失败。

我会使用变量来报告文件的存在。

public void Main()
{ 
string targetfile = Dts.Variables["PRC_file_path"].Value.ToString();
 if (File.Exists(targetfile))
            {
                Dts.Variables["file_exists"].Value = true;
            }
            else
            {
                 Dts.Variables["file_exists"].Value = false;
            }
Dts.TaskResult = (int)ScriptResults.Success;
}

您希望脚本本身成功,除非它遇到错误。

更好的是:

public void Main()
{ 
string targetfile = Dts.Variables["PRC_file_path"].Value.ToString();
  try{
 if (File.Exists(targetfile))
            {
                Dts.Variables["file_exists"].Value = true;
            }
            else
            {
                 Dts.Variables["file_exists"].Value = false;
            }
     Dts.TaskResult = (int)ScriptResults.Success;
     }
 catch (Exception Ex)
     {
     Dts.TaskResult = (int)ScriptResults.Failure;
     }
}

编辑:

忘了提到您需要将优先约束从 CONSTRAINT 切换到表达式和约束,其中表达式计算@file_exists变量。 您应该有两条成功路径,一条是变量评估为 true,另一条为 false。

最新更新