我有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