2

Can I select rows on row version?

I am querying a database table periodically for new rows. I want to store the last row version and then read all rows from the previously stored row version.

I cannot add anything to the table, the PK is not generated sequentially, and there is no date field.

Is there any other way to get all the rows that are new since the last query?

I am creating a new table that contains all the primary keys of the rows that have been processed and will join on that table to get new rows, but I would like to know if there is a better way.

EDIT

This is the table structure:

enter image description here

Everything except product_id and stock_code are fields describing the product.

4

2 回答 2

3

您可以将 rowversion 转换为 bigint,然后在再次读取行时将列转换为 bigint 并与之前存储的值进行比较。这种方法的问题是每次您根据行版本的演员选择表扫描 - 如果您的源表很大,这可能会很慢。

我还没有尝试过这个的持久计算列,我很想知道它是否运作良好。

示例代码(在 SQL Server 2008R2 中测试):

DECLARE @TABLE TABLE
(
    Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Data VARCHAR(10) NOT NULL,
    LastChanged ROWVERSION NOT NULL
)

INSERT INTO @TABLE(Data)
VALUES('Hello'), ('World')

SELECT
    Id,
    Data,
    LastChanged,
    CAST(LastChanged AS BIGINT)
FROM
    @TABLE  

DECLARE @Latest BIGINT = (SELECT MAX(CAST(LastChanged AS BIGINT)) FROM @TABLE)

SELECT * FROM @TABLE WHERE CAST(LastChanged AS BIGINT) >= @Latest

编辑:看来我误解了,你实际上并没有 ROWVERSION 列,你只是提到了行版本作为一个概念。在这种情况下,SQL Server Change Data Capture 将是我能想到的唯一符合要求的东西:http ://technet.microsoft.com/en-us/library/bb500353(v=sql.105).aspx

不确定这是否符合您的需求,因为您需要能够存储“上次查看时间”的 LSN,以便正确查询 CDC 表。它更适合于数据加载,而不是典型的查询。

于 2013-10-08T07:56:04.357 回答
1

假设您可以创建一个临时表,该EXCEPT命令似乎是您所需要的:

  1. 将您的表复制到临时表中。
  2. 下次您查看时,从您的表中选择所有内容,除了临时表中的所有内容,从中提取您需要的键
  3. 确保您的临时表是最新的。

请注意,您的临时表只需要包含您需要的键。如果这只是一列,您可以选择 aNOT IN而不是EXCEPT.

于 2013-10-08T09:51:57.997 回答