为了在我们的测试工具中使用,我试图查找自上次运行以来 SQL Server 表中所有添加和/或修改的行。
是否有人有一个从表中选择最高版本 (dbtype
timestamp
) 的 SQL 或 Linq 语句,以及另一个选择版本高于第一步检索到的值的所有行的 SQL 或 Linq 语句?
此代码将选择迄今为止最高的行版本。
private static byte[] GetVersionMark(string name)
{
SqlCommand command;
byte[] version;
using (SqlConnection connection = new SqlConnection(GetConnectionString(name)))
{
connection.Open();
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT @@DBTS";
version = (byte[])command.ExecuteScalar();
connection.Close();
command.Dispose();
}
}
问题是我找不到代码来使用检索到的
version
类型的 byte[8]
来查找更改的行,因为数组类型不允许“大于”。
您可以在数值上使用 System.Memory(或 IPAddress.NetworkToHostOrder)中的 BinaryPrimitives.ReverseEndianness。
在我的 C# 代码(绑定到实体框架)中,我使用了类似以下内容:
[Timestamp]
public byte[] RecordTimestamp { get; set; } = new byte[sizeof(UInt64)];
private UInt64? _FriendlyRecordTimestamp;
[NotMapped]
public UInt64 FriendlyRecordTimestamp => _FriendlyRecordTimestamp ??= BinaryPrimitives.ReverseEndianness(BitConverter.ToUInt64(this.RecordTimestamp, 0));
在 T-SQL 中你也可以尝试类似的方法
SELECT CONVERT (binary(8), REVERSE (ROWTIMESTAMP)) FROM TABLE
或
SELECT CONVERT(bigint, CONVERT(binary(8), REVERSE (ROWTIMESTAMP))) FROM TABLE