寻找一种方法是SQL Server
表1 - Status_Latest
DeviceID Status(bit) TimeOfUpdate(datetime)
表2 - Status_History
DeviceID Status(bit) TimeOfUpdate(datetime)
寻找实现这一目标的最快方法:
调用存储过程,它传递DeviceID
和状态。
如果DeviceID
中不存在Status_Latest
,请同时插入Status_Latest
和Status_History
如果值与Status_Latest
中的当前值不同,请更新它
并存储到Status_History
我在想
选项A:如果值不同,我可以从Status_Latest
中选择,然后更新Status_Latest
和Status_History
。
选项B:我可以在存储旧值时更新Status_Latest
吗?
如果值不同,请更新Status_Latest
和Status_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())
答案 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