Wednesday, March 23, 2016

How to Update DataTable and Commit it to the Database

In SSIS Script Task, it seems helpful to use a select statement to consturct a DataTable, update the DataTable as necessary, and commit the DataTable back to database's table. Below is a working example of this case.

protected int updateDeathLog()
{
    int retVal = 0;
    string connString = Dts.Variables["ConnString1"].Value.ToString();
    string sql = "SELECT ObjectId, NewFileName, PageNum, TargetFileExists, TargetFileExistsDT " +
            "FROM MyTable WHERE SourceFileExists = 1 AND TargetFileExists = 0";

    using (SqlConnection conn = new SqlConnection(connString))
    {
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            string newFileFullPath = String.Empty;

            DataTable dt = new DataTable();
            adapter.Fill(dt);
            foreach(DataRow row in dt.Rows)
            {
                // If files exists in target folder, update flags and 
                // datetime field in the DataTable.
                newFileFullPath = Dts.Variables["TargetFolderDeath"].Value.ToString()
                  + "\\" + row["NewFileName"].ToString();

                if(File.Exists(newFileFullPath))
                {
                    row["TargetFileExists"] = true;
                    row["TargetFileExistsDT"] = DateTime.Now;
                }
                else
                {
                    row["TargetFileExists"] = false;
                    row["TargetFileExistsDT"] = System.DBNull.Value;
                }
            }

            // Commit update DataTable to the MyTable.
            // Prior to the commit, set up primary keys in the DataTable 
            // and create a CommandBuilder.
            DataColumn[] keyColumns = new DataColumn[2];
            keyColumns[0] = dt.Columns["ObjectId"];
            keyColumns[1] = dt.Columns["PageNum"];
            dt.PrimaryKey = keyColumns;

            SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter);
            adapter.Update(dt);

            retVal = dt.Rows.Count;
        }
        catch (Exception ex)
        {
            retVal = -1;
            errorMsg = ex.Message;
            stackTrace = ex.StackTrace;
        }
    }

return retVal;
}

No comments: