我有08年的SQL表看起來像這樣:SQL更新是否存在及以上,否則插入
DECLARE @DataTable TABLE
(
Name varchar(10),
[TimeStamp] DateTime,
Event varchar(10),
Data varchar(10)
)
INSERT INTO @DataTable
VALUES ('TEST01', '2012/03/06 10:00', 'EventA', 1),
('TEST01', '2012/03/06 10:01', 'EventB', 2),
('TEST01', '2012/03/06 11:00', 'EventC', 0)
我會怎麼做在SQL如下:
If DataTable contains row where Name = @NewName and Event = @NewEvent Then
If TimeStamp of the above row < @NewTimeStamp
Update that row with new TimeStamp and Data
EndIf
Else
Insert row into table
EndIf
對於例如,我有以下三個數據點和他們預期的操作:
('TEST01', '2012/03/06 10:01', 'EventA', 5), -- This should update the existing row because it's a newer EventA
('TEST01', '2011/01/01 9:00', 'EventB', 2), -- This should be discarded because a newer EventB data point exists in the table
('TEST01', '2011/05/12 17:00', 'EventD', 0), -- This should be inserted because no row in the table contains EventD
非常棒 - 我想你只需要擺脫第二個「WHEN MATCHED」塊。 – 2012-03-08 14:41:55