我想在我的python程序中对表进行Upsert。我找到了MERGE命令,但这似乎特定于合并两个表。我想从一个查询中将字段更新/插入表中。
我想要比DELETE更快的东西然后INSERT或SELECT然后[INSERT / UPDATE]并且我想让MERGE工作。但是,当我在SSMS中运行它时,它正在更新所有数据库表中的行。
查询是:
MERGE INTO [LastPriceUpdate] USING
(SELECT [EventID] FROM [LastPriceUpdate] where [EventID] = 1501845) AS source
ON (source.[EventID] = 1501845)
WHEN MATCHED THEN UPDATE SET [LastPriceUpdate] = getdate() -- where clause not allowed
WHEN NOT MATCHED BY TARGET THEN INSERT ([EventID], [LastPriceUpdate]) VALUES (1501845, getdate());
该查询更新所有行,我只希望它使用getdate()更新LastPriceUpdate列,其中EventID = {somenumber}
可能的答案: 这可能是一个修复;在ON部分使用目标。
MERGE INTO [LastPriceUpdate] AS target USING
(SELECT [EventID] FROM [LastPriceUpdate] where [EventID] = 1501845) AS source
ON (target.[EventID] = 1501845)
WHEN MATCHED THEN UPDATE SET [LastPriceUpdate] = getdate() -- where clause not allowed
WHEN NOT MATCHED BY TARGET THEN INSERT ([EventID], [LastPriceUpdate]) VALUES (1501845, getdate());
答案 0 :(得分:3)
我认为你正在寻找类似的东西。
MERGE INTO LastPriceUpdate as lpu
USING (
SELECT getdate() as LastPriceUpdate,
1501845 as EventID
) AS src
ON lpu.EventID = src.EventID
WHEN MATCHED THEN
UPDATE SET LastPriceUpdate = src.LastPriceUpdate
WHEN NOT MATCHED BY TARGET THEN
INSERT (EventID, LastPriceUpdate)
VALUES (src.EventID, src.LastPriceUpdate);