用于存储最新值和历史记录表的SQL Server存储过程

时间:2015-09-01 17:25:06

标签: sql sql-server stored-procedures database-design

寻找一种方法是SQL Server

表1 - Status_Latest

DeviceID Status(bit) TimeOfUpdate(datetime)

表2 - Status_History

DeviceID Status(bit) TimeOfUpdate(datetime)

寻找实现这一目标的最快方法:

调用存储过程,它传递DeviceID和状态。

如果DeviceID中不存在Status_Latest,请同时插入Status_LatestStatus_History

如果值与Status_Latest中的当前值不同,请更新它 并存储到Status_History

我在想

选项A:如果值不同,我可以从Status_Latest中选择,然后更新Status_LatestStatus_History

选项B:我可以在存储旧值时更新Status_Latest吗? 如果值不同,请更新Status_LatestStatus_History

到目前为止我所拥有的内容(仅在应用程序中调用,需要在DB存储过程中处理)

insert into [SensorStateChange_History] (SensorIndex, SensorOccupied, TimeOfDataBaseStorage)
values (@SensorIndex, @SensorOccupied, GETUTCDATE())

update SensorState_Latest
set SensorOccupied = @SensorOccupied, 
    TimeOfDataBaseStorage = GETUTCDATE()
and SensorIndex = @SensorIndex

if @@ROWCOUNT = 0

insert into SensorState_Latest
values (@SensorIndex, @SensorOccupied, GETUTCDATE())

1 个答案:

答案 0 :(得分:1)

我将如何做到这一点:

IF NOT EXISTS(SELECT * FROM [SensorStateChange_Latest] WHERE SensorIndex=@SensorIndex AND SensorOccupied=@SensorOccupied)
  BEGIN
  update SensorState_Latest
  set SensorOccupied = @SensorOccupied, 
    TimeOfDataBaseStorage = GETUTCDATE()
  WHERE SensorIndex = @SensorIndex;    

  if @@ROWCOUNT = 0    
    insert into SensorState_Latest
    values (@SensorIndex, @SensorOccupied, GETUTCDATE())

  insert into [SensorStateChange_History] (SensorIndex, SensorOccupied, TimeOfDataBaseStorage)
  values (@SensorIndex, @SensorOccupied, GETUTCDATE());

  END