Search code examples
c#sql-server-2008change-data-capture

How to compare SQL Server CDC LSN values in C#?


In SQL its easy as it supports the binary(10) LSN values for comparison:

SELECT *, __$start_lsn, __$seqval
FROM cdc.fn_cdc_get_all_changes_dbo_sometable(@startLsn, @endLsn, 'all update old') 
WHERE __$seqval > @seqval 
ORDER BY __$start_lsn, __$seqval

In C# it's more difficult:

byte[] mySeqval = ...
foreach(var row in cdcData)
{
    if(row.seqval > mySeqval) // Cannot perform this
        ...
}

Can the LSN / SeqVal values be converted into a number than can be compared easily? These are 10 bytes (80 bits) in size.

My project is in .Net 3.5


Solution

  • Didn't need to use any of the above in the end. Ony of my collegues solved the problem in the end (Thanks Tony Broodie). The way to do this was to compare to seqval, then take+1. Simples.

    SqlExecutor.ExecuteReader(cnn,
    string.Format("SELECT {0} , __$start_lsn, __$seqval , __$update_mask " +
        "FROM cdc.fn_cdc_get_all_changes_{1}(@startLsn,@endLsn,'all update old') cdc {2} " +
        "where __$operation = {3} ORDER BY __$start_lsn, __$seqval", columns,
        captureInstance, joins, (int)operation), 
        reader =>
        {
            if (reader != null)
                items.Add(createEntity(reader));
        }, 5, 60, new SqlParameter("@startLsn", lsn), 
                  new SqlParameter("@endLsn", endLsn));
    });
    startLsn = lsn;
    seqVal = sequence;
    var startIndex = sequence == null ? 0 : 
      items.FindIndex(0, item => item.Lsn.SequenceEqual(lsn)
        && item.Seqval.SequenceEqual(sequence)) + 1; // <---- Look here. See the +1
    return items.Skip(startIndex).ToList();