我在SQL 2008中有一个表格如下:
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
答案 0 :(得分: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)
答案 1 :(得分:0)
也许是这样的:
IF EXISTS
(
SELECT
NULL
FROM
@DataTable AS DataTable
WHERE
DataTable.Event=@NewEvent
AND DataTable.Name=@NewName
)
BEGIN
IF EXISTS
(
SELECT
NULL
FROM
@DataTable AS DataTable
WHERE
DataTable.Event=@NewEvent
AND DataTable.Name=@NewName
AND DataTable.TimeStamp<@NewTimeStamp
)
BEGIN
UPDATE @DataTable
SET TimeStamp=@NewTimeStamp,
Data=@NewData
WHERE
Event=@NewEvent
AND Name=@NewName
AND TimeStamp<@NewTimeStamp
END
END
ELSE
BEGIN
INSERT INTO @DataTable(Data,Event,Name,TimeStamp)
VALUES(@NewData,@NewEvent,@NewName,@NewTimeStamp)
END
答案 2 :(得分:0)
您只需检查存在参数的行
即可IF EXISTS (SELECT * FROM @DataTable WHERE Name = @newName AND Event = @newEvent)
BEGIN
IF EXISTS (SELECT * FROM @DataTable WHERE Name = @newName AND Event = @newEvent AND TimeStamp < @newTimeStamp)
--Update
UPDATE @DataTable
SET TimeStamp=@NewTimeStamp,
Data=@NewData
WHERE
Event=@NewEvent
AND Name=@NewName
END
ELSE
BEGIN
--insert
END
答案 3 :(得分:0)
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;