Компонент сценариев SSIS: получение дочерних записей для создания объекта - PullRequest
1 голос
/ 12 сентября 2011

Получил работу - Опубликовано мое решение ниже, но хотел бы знать, если есть лучший способ

Привет всем

Я пытаюсь создать событие домена для вновь созданного (после миграции) объекта домена в моей базе данных.

для объектов без каких-либо внутренних дочерних объектов он работал нормально с использованием компонента Script. Проблема заключается в том, как заставить дочерние строки добавлять информацию в объект события.

Ex. Клиент-> Расположение клиентов.

Я создаю событие в компоненте сценария - как преобразование - (ссылаюсь на модуль событий моего домена), а затем создаю отправку сериализованной информации о событии в виде значения столбца. Входные строки в настоящее время предоставляют данные для родительского объекта.

Пожалуйста, сообщите.

С уважением,

Март

Редактировать 1

Я бы хотел добавить ток, который я выполняю, в

public override void Input0_ProcessInputRow(Input0Buffer Row)

Я ищу что-то вроде создания программы чтения данных в этой функции

цикл по строкам данных -> создать дочерний объект и добавить его в родительскую совокупность

Все еще на Google и PreExecute и ProcessInput Кажется, что-то посмотреть. enter image description here

1 Ответ

1 голос
/ 13 сентября 2011

Это моё решение. Я полностью новичок в SSIS, так что это может быть не лучшим решением.

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    IDTSConnectionManager100 connectionManager;
    SqlCommand cmd = null;
    SqlConnection conn = null;
    SqlDataReader reader = null;


    public override void AcquireConnections(object Transaction)
    {

        try
        {
            connectionManager = this.Connections.ScriptConnectionManager;
            conn = connectionManager.AcquireConnection(Transaction) as SqlConnection;

            // Hard to debug failure-  better off logging info to file
            //using (StreamWriter outfile =
            //    new StreamWriter(@"f:\Migration.txt"))
            //{
            //    outfile.Write(conn.ToString());
            //    outfile.Write(conn.State.ToString());
            //}
        }
        catch (Exception ex)
        {
            //using (StreamWriter outfile =
            //    new StreamWriter(@"f:\Migration.txt"))
            //{
            //    outfile.Write(" EEEEEEEEEEEEEEEEEEEE"+ ex.ToString());
            //}
        }




    }


    public override void PreExecute()
    {
        base.PreExecute();

        cmd = new SqlCommand("SELECT [CustomerLocation fields] FROM customerlocationView where custid=@CustId", conn);
        cmd.Parameters.Add("CustId", SqlDbType.UniqueIdentifier);

    }

    public override void PostExecute()
    {
        base.PostExecute();
        /*
          Add your code here for postprocessing or remove if not needed
          You can set read/write variables here, for example:
          Variables.MyIntVar = 100
        */
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        Collection<CustomerLocation> locations = new Collection<CustomerLocation>();
        cmd.Parameters["CustId"].Value = Row.id;

        // Any error always  saw that reader reamians open on connection
        if (reader != null)
        {
            if (!reader.IsClosed)
            {
                reader.Close();
            }
        }

        reader = cmd.ExecuteReader();

        if (reader != null)
        {
            while (reader.Read())
            {
                // Get Child Details
                var customerLocation = new CustomerLocation(....,...,...,);
                customerLocation.CustId = Row.id;
                locations.Add(customerLocation);
            }



        }






        var newCustomerCreated = new NewCustomerCreated(Row.id,,...,...,locations);

        var serializedEvent = JsonConvert.SerializeObject(newCustomerCreated, Formatting.Indented,
                                                                    new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

        Row.SerializedEvent = serializedEvent;
        Row.EventId = newCustomerCreated.EventId;
        ...
        ...
        ...
        ....
        ..
        .
        Row.Version = 1;



       // using (StreamWriter outfile =
        //       new StreamWriter(@"f:\Migration.txt", true))
       // {
       //     if (reader != null)
         //   {
         //       outfile.WriteLine(reader.HasRows);
            //outfile.WriteLine(serializedEvent);
          //  }
           // else
          //  {
          //      outfile.Write("reader is Null");
          //  }
        //}
        reader.Close();
    }



    public override void ReleaseConnections()
    {
        base.ReleaseConnections();
        connectionManager.ReleaseConnection(conn);
    }
}

Следует отметить, что другой подход к созданию соединения заключается в получить строку соединения из connectionManager и использовать ее для создания соединения OLEDB.

...