SSIS - Convert a variable value to expression

Problem:

I have a SSIS package where I am running a SQL execution task to get some records, Then I am running a foreach loop iterating over ADO object returned and setting few variables values.
These variables are used for data flow task queries. I need to set expression for the variable.
In rows I have value something similar to "foo" + @[User::Bar] + "baz" (I set it using this expression directly, it works. I want to set it from sql output)
But when I get this value from SQL task to Variable expression, SSIS is escaping the quotes, I do not want to escape these for my task to work.
Saved Value : "foo" + @[User::Bar] + "baz"
Variable set : \"foo\" + @[User::Bar] + \"baz\"
Can anyone help me with this. I want expression as I have saved, due to this forceful escaping, my query is not getting set properly.

Solution:

1st approach - Removing escape character using SSIS expression

(This approach will only remove escape character)
If the following value is stored within a variable (example @[User::Var1]:
\"foo\" + @[User::Bar] + \"baz\"
Add an Expression task with the following expression:
@[User::Var1] = REPLACE(@[User::Var1],"\\","")
Or create an new variable with the following expression:
REPLACE(@[User::Var1],"\\","")

Experiments

I created a variable @[User::Variable] of type string with the following value:
\"foo\" + @[User::Bar] + \"baz\"
Then i created another variable @[User::Variable1] of type string with the following expression:
REPLACE( @[User::Variable],"\\","")
The value escape characters are gone:
enter image description here

2nd approach - Convert Value to expression

Since you are looking to treat the following value \"foo\" + @[User::Bar] + \"baz\" as an expression and not a fixed value. You cannot achieve that using SSIS expression. You have to assign this value as expression to another variable as mentioned below:
I added 3 variable into my package: BarVar1, and VarResult
enter image description here
I added a Script task and selected Var1 as Readonly variable and VarResult as ReadWriteVariable:
enter image description here
Inside the script i used the following code to assign the value of Var1 as expression into VarResultafter removing escape character:
public void Main()
{
    string Var1 = Dts.Variables["Var1"].Value.ToString();

    Dts.Variables["VarResult"].Expression = Var1.Replace("\\", "");
    Dts.Variables["VarResult"].EvaluateAsExpression = true;

    Dts.TaskResult = (int)ScriptResults.Success;
}
Result
enter image description here

Comments

Popular posts from this blog

SSIS - Script Task error: Exception has been thrown by the target of an invocation.

Don’t install Hadoop on Windows!

SSIS - script component DateTime Formats Implicit Conversion