【问题标题】:MERGE - to replace ON Duplicate with sql serverMERGE - 用 sql server 替换 ON Duplicate
【发布时间】:2015-05-09 18:55:03
【问题描述】:

我主要使用 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

但老实说,这个例子有点过分,令人眼花缭乱。有人可以为我简化它以适应我的示例,以便我更好地理解它吗?

【问题讨论】:

  • 也就是说,如果条目中存在'unlimited',你想更新,对吧?
  • 是,如果记录存在,将其设置为受限

标签: sql sql-server azure merge


【解决方案1】:

为了进行合并,合并语句需要某种形式的源表/表变量。然后就可以进行合并了。所以可能是这样的(注意:没有完全检查语法,提前道歉):

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';

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 2011-01-14
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多