Breaking News
Loading...
25/06/2013

SSIS - Lấy giá trị từ dòng trước

Như ta biết khi xử lý dữ liệu trong Data Flow, từng dòng từng dòng sẽ được xử lý. Nếu ta muốn lấy những giá trị của dòng trước đó thì làm thế nào?

Câu trả lời chỉ đơn giản là dùng Script Component Transformation.

Như kịch bản dưới đây, tác giả có 1 file như sau:


Có vẻ như dữ liệu của cột Month đã bị thiếu. Nhưng nếu ta muốn lấy giá trị Jan, Feb, Mar điền vào những ô trống tương ứng bên dưới thì cũng làm được dễ dàng trong SSIS.

Dùng Script Component, đổi thuộc tính của cột Month là ReadWrite như hình sau:


Sau đó ta dùng đoạn code xử lý sau, lưu giá trị của dòng trước đó vào 1 biên là LastValue

/* Microsoft SQL Server Integration Services Script Component
*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
    private string LastValue = "";
    public override void PreExecute()
    {
        base.PreExecute();
        /*
          Add your code here for preprocessing or remove if not needed
        */
    }
    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)
    {
        if (Row.Month_IsNull == true)
        {
            Row.Month = LastValue;
        }
        else
        {
            LastValue = Row.Month;
        }
    }
}
Vậy là xong.

Tham khảo: http://ericwisdahl.wordpress.com/2009/08/02/ssis-retain-values-from-previous-rows/

0 comments:

Post a Comment

 
Toggle Footer