【问题标题】:How do I use a package variable inside a Script task?如何在脚本任务中使用包变量?
【发布时间】:2011-08-06 09:38:57
【问题描述】:

目前,我在 SSIS 包的脚本任务中硬编码了一个文件路径值。

我有一个字符串变量 sPath。我应该如何在脚本任务中使用这个变量 sPath?

string strPath = "C:\\File.xls";
if( File.Exists(strPath))
{
    File.Delete(strPath);
}

【问题讨论】:

    标签: sql-server sql-server-2008 ssis


    【解决方案1】:

    这是在Script Task 中使用变量的一种可能方式。假设您在包中声明了一个名为 FilePath 的变量,如屏幕截图 #1 所示,那么您可以使用以下代码来使用 Script Task 中的变量。这是使用变量的可能方法之一。这里的变量仅用于使用LockForRead 方法读取值。如果变量是使用LockForWrite 方法声明的,您也可以将值写入变量。

    顺便说一下,Scrip Task 代码中描述的功能也可以使用 SSIS Control Flow 任务列表中的File System Task 来执行。

    希望对您有所帮助。

    在脚本任务中使用包变量:

    C# 代码只能在 SSIS 2008 and above 中使用。 .

    public void Main()
    {
        Variables varCollection = null;
        string FilePath = string.Empty;
    
        Dts.VariableDispenser.LockForRead("User::FilePath");
        Dts.VariableDispenser.GetVariables(ref varCollection);
    
        FilePath = varCollection["User::FilePath"].Value.ToString();
    
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
    
        varCollection.Unlock();
    
        Dts.TaskResult = (int)ScriptResults.Success;
    }
    

    屏幕截图 #1:

    【讨论】:

    • 这就是完美的答案!谢谢
    • 不知道为什么这没有被接受。很有帮助,谢谢。
    • 我们应该在 using 语句中包含哪些命名空间,以便编译器解析 Variables 声明?在调用GetVariables 方法时,我必须将Variables 替换为IDTSVariables100,并将ref 修饰符替换为out。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多