Paul Kar.
Paul Kar.

Reputation: 1324

Add a derived column to a table via C# script in SSIS

I would like to calculate a hash function (using MD5) and add a column to the existing table with the result. I am using a script task in SSIS to write a short C# script. Here is my script:

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    public override void PreExecute()
    {
        base.PreExecute();
        /*
         * Add your code here
         */
    }

    public override void PostExecute()
    {
        base.PostExecute();
        /*
         * Add your code here
         */
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        /*
         * Add your code here
         */
        using (MD5 md5Hash = MD5.Create())
        {
            string hash = GetMd5Hash(md5Hash, Row);
            MessageBox.Show(hash);
        }
    }

    static string GetMd5Hash(MD5 md5Hash, Input0Buffer input)
    {

        // Convert the input string to a byte array and compute the hash. 
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input.ToString()));

        // Create a new Stringbuilder to collect the bytes 
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data  
        // and format each one as a hexadecimal string. 
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string. 
        return sBuilder.ToString();
    }

}

My SSIS package looks like this: How my SSIS package looks like this I am simply grabbing a table from a database with one row. I would like to hash all the columns, create another column and store the result of the hash there. I am able to generate the hash, but I don't know how to add a column to the result set and insert the value of the hash to that column. Any help would be appreciated. Thanks.

Upvotes: 3

Views: 1977

Answers (1)

gj12
gj12

Reputation: 11

To assign the column in c# as you asked in reply to billinkc your code would look like:

public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        /*
         * Add your code here
         */
        using (MD5 md5Hash = MD5.Create())
        {
            //string hash = GetMd5Hash(md5Hash, Row);
            Row.MyOutputColumn = GetMd5Hash(md5Hash, Row);
            //MessageBox.Show(hash);
        }
    }

Upvotes: 1

Related Questions