如何在脚本组件中访问ssis包变量

时间:2012-11-19 08:49:04

标签: c# sql database ssis bids

如何访问我在数据流中使用的C#代码中的变量 - >脚本组件 - >我的c#脚本带有我的SSIS包吗?

我已经尝试过哪个也无法正常工作

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

6 个答案:

答案 0 :(得分:54)

在脚本组件(数据流任务)中访问包变量与在脚本任务中访问包变量不同。对于脚本组件,首先需要打开Script Transformation Editor(右键单击组件并选择“编辑...”)。在“脚本”选项卡的“自定义属性”部分中,您可以以只读或读写方式输入(或选择)要使脚本可用的属性: screenshot of Script Transformation Editor properties page 然后,在脚本本身中,变量将作为Variables对象的强类型属性提供:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

一个重要的警告:如果你需要到一个包变量,你只能在PostExecute()方法中这样做。

关于代码段:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection初始化为null,永远不会设置为有效值。因此,任何尝试取消引用它都会失败。

答案 1 :(得分:3)

首先在脚本任务编辑器中的ReadOnlyVariables中列出要在脚本任务中使用它们的变量并编辑脚本

在脚本代码中使用ReadOnlyVariables

String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();

这行代码会将ssis包变量视为字符串。

答案 2 :(得分:1)

  • 在变量脚本的前端属性页面上,修改ReadOnlyVariables(或ReadWriteVariables)属性并选择您感兴趣的变量。这将启用脚本任务中的选定变量
  • 在代码中,您现在可以将变量读取为

    string myString = Variables.MyVariableName.ToString();

答案 3 :(得分:1)

我遇到了与OP相同的问题,除了我记得声明ReadOnlyVariables。

经过一番游戏后,我发现这是我变量的名称。 " FILE_PATH"在SSIS中某种程度上转换为" FilePath"。 C#与变量名中的下划线不能很好地匹配。

所以要访问变量,我输入

string fp = Variables.FilePath;

在脚本组件的PreExecute()方法中。

答案 4 :(得分:0)

强类型var似乎不可用,我必须执行以下操作才能访问它们:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

答案 5 :(得分:0)

这应该有效:

IDTSVariables100 vars = null;
VariableDispenser.LockForRead("System::TaskName");
VariableDispenser.GetVariables(vars);
string TaskName = vars("System::TaskName").Value.ToString();
vars.Unlock();

您的初始代码没有调用GetVariables()方法。