1

Many times I need to move the data of a large table (let's call it source) to a clone of it (let's call it target). Due to the large size, instead of just deleting/inserting all, I prefer to upsert.

For easiness, let's assume an int PK col named "id".

Until now, in order to do this, I've used the datetime field dbupddate, existent on both tables, which holds the most recent time the row was inserted/updated. This is done by using a trigger which, for any insert/updates, sets dbupddate to getdate().

Thus, my run-of-the-mill upsert code until now looks something like:

update t set (col1=s.col1,col2=s.col2 etc)
from source s
inner join target t on s.id=t.id and s.dbupddate>t.dbupddate

insert target 
select * from source s
where not exists (select 1 from target t where t.id=s.id)

Recently I stumbled on rowversion. I have read and understood up to an extent its function, but I'd like to know practically what benefits/drawbacks there are in case I change dbupddate to rowversion instead of datetime.

George Menoutis
  • 6,894
  • 3
  • 19
  • 43
  • 1
    For starters, `ROWVERSION` carries no semantics beyond the transaction order -- it will not allow you to say anything about *when* the row was updated, it will not allow you to group related updates (at least not easily) and it will not work if you need to reconcile changes over multiple databases (as they each have their own `ROWVERSION`). Conversely, `DATETIME` is a rather poor type to use even if you do need chronological ordering, due to its limited precision and rounding issues. At least `DATETIME2` should be considered. – Jeroen Mostert Aug 21 '18 at 12:22
  • Also, if you find yourself "cloning" data like this manually, at least check if SQL Server's built in replication features can't do what you want. This sounds like a good candidate for transactional replication. – Jeroen Mostert Aug 21 '18 at 12:25

1 Answers1

0

Although datetime carries information that may be useful in some cases, rowversion is more reliable since system datetime is always at the risk of getting changed and losing accuracy. In your case, I personally prefer rowversion for its reliability.

Amir Molaei
  • 3,700
  • 1
  • 17
  • 20