I’ve got a table in SQL 2008 that looks like this:
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)
How would I do the following in 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
For example, I’ve got the following three data points and their expected actions:
('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
1 Answer