我有一个每天加载新数据的表和另一个包含该表更改历史的表。检查自上次加载数据以来是否有任何数据发生更改的最佳方法是什么?
例如,我有针对不同国家/地区的一些策略的表@a,表@b 跟踪对表@a 所做的更改。我可以使用 checksum() 对可以更改的字段进行散列,如果现有散列与新散列不同,则将它们添加到表中。然而,MSDN 认为这不是一个好主意,因为可能会发生“冲突”,例如,两个不同的值映射到同一个校验和。
校验和的 MSDN 链接 http://msdn.microsoft.com/en-us/library/aa258245(v=SQL.80).aspx
示例代码:
declare @a table
(
ownerid bigint
,Strategy varchar(50)
,country char(3)
)
insert into @a
select 1,'Long','USA'
insert into @a
select 2,'Short','CAN'
insert into @a
select 3,'Neutral','AUS'
declare @b table
(
Lastupdated datetime
,ownerid bigint
,Strategy varchar(50)
,country char(3)
)
insert into @b
(
Lastupdated
,ownerid
,strategy
,country
)
select
getdate()
,a.ownerid
,a.strategy
,a.country
from @a a left join @b b
on a.ownerid=b.ownerid
where
b.ownerid is null
select * from @b
--get a different timestamp
waitfor delay '00:00:00.1'
--change source data
update @a
set strategy='Short'
where ownerid=1
--add newly changed data into
insert into @b
select
getdate()
,a.ownerid
,a.strategy
,a.country
from
(select *,checksum(strategy,country) as hashval from @a) a
left join
(select *,checksum(strategy,country) as hashval from @b) b
on a.ownerid=b.ownerid
where
a.hashval<>b.hashval
select * from @b