2012-03-08 66 views
0

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

回答

4
merge @DataTable as dt 
using (select @data as data, @event as event, @name as name, @timestamp as timestamp) source 
on dt.name=source.name and dt.event=source.event 
when matched and dt.timestamp <= source.timestamp then 
    update 
    set timestamp = source.timestamp, data = source.data 
when matched and dt.timestamp > source.timestamp then 
    insert(data, event, name, timestamp) 
    values(data, event, name, timestamp) 
when not matched then 
    insert(data, event, name, timestamp) 
    values(data, event, name, timestamp) 
+0

非常棒 - 我想你只需要擺脫第二個「WHEN MATCHED」塊。 – 2012-03-08 14:41:55

0

也許是這樣的:

IF EXISTS 
    (
     SELECT 
      NULL 
     FROM 
      @DataTable AS DataTable 
     WHERE 
      [email protected] 
      AND [email protected] 
    ) 
BEGIN 
    IF EXISTS 
    (
     SELECT 
      NULL 
     FROM 
      @DataTable AS DataTable 
     WHERE 
      [email protected] 
      AND [email protected] 
      AND DataTable.TimeStamp<@NewTimeStamp 
    ) 
    BEGIN 
     UPDATE @DataTable 
     SET [email protected], 
      [email protected] 
     WHERE 
      [email protected] 
      AND [email protected] 
      AND TimeStamp<@NewTimeStamp 
    END 
END 
ELSE 
BEGIN 
    INSERT INTO @DataTable(Data,Event,Name,TimeStamp) 
    VALUES(@NewData,@NewEvent,@NewName,@NewTimeStamp) 
END 
+0

存在行,但不會增加新的行如果數據比現有數據舊? – AbstractChaos 2012-03-08 11:56:18

+0

更新了答案' – Arion 2012-03-08 12:07:34

0
BEGIN TRANSACTION; 
UPDATE dbo.table SET ... WHERE PK = @PK; 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT dbo.table(PK, ...) SELECT @PK, ...; 
END 
COMMIT TRANSACTION; 
相關問題