我主要使用mySQL,所以转移到azure和sql server我意识到复制不起作用。
我试图这样做:
INSERT INTO records (jid, pair, interval, entry) VALUES (1, 'alpha', 3, 'unlimited') ON DUPLICATE KEY UPDATE entry = "limited";
但当然,在此处不允许使用重复键。所以MERGE是正确的形式。
我看过: https://technet.microsoft.com/en-gb/library/bb522522(v=sql.105).aspx
但说实话,这个例子有点过分,令人垂涎欲滴。有人可以愚蠢地让我适应我的榜样,这样我可以更好地理解它吗?
答案 0 :(得分:3)
为了进行合并,您需要某种形式的源表/表var用于merge语句。然后你可以进行合并。所以可能有些事情(注意:没有完全语法检查,提前道歉):
WITH src AS (
-- This should be your source
SELECT 1 AS Id, 2 AS Val
)
-- The above is not neccessary if you have a source table
MERGE Target -- the detination table, so in your case records
USING src -- as defined above
ON (Target.Id = src.Id) -- how do we join the tables
WHEN NOT MATCHED BY TARGET
-- if we dont match, what do to the destination table. This case insert it.
THEN INSERT(Id, Val) VALUES(src.Id, src.Val)
WHEN MATCHED
-- what do we do if we match. This case update Val
THEN UPDATE SET Target.Val = src.Val;
请勿忘记阅读正确的语法页面:https://msdn.microsoft.com/en-us/library/bb510625.aspx
我认为这转化为你的例子(tm):
WITH src AS (
-- This should be your source
SELECT 1 AS jid, 'alpha' AS pair, 3 as 'interval'
)
MERGE records -- the detination table, so in your case records
USING src -- as defined above
ON (records.Id = src.Id) -- how do we join the tables
WHEN NOT MATCHED BY TARGET
-- if we dont match, what do to the destination table. This case insert it.
THEN INSERT(jid, pair, interval, entry) VALUES(src.jid, src.pair, src.interval, 'unlimited')
WHEN MATCHED
-- what do we do if we match. This case update Val
THEN UPDATE SET records.entry = 'limited';