Using SQL Server MERGE command with same source & target table

后端 未结 2 1658
自闭症患者
自闭症患者 2021-01-03 14:11

I\'m trying to insert or update a single table using the MERGE command however I always get a \"0 rows affected\". My goal is simple: if exists update, otherwise insert. Wha

2条回答
  •  礼貌的吻别
    2021-01-03 14:30

    I think you're wanting to insert a new value if there isn't currently one matching by date, sip, dip and port, but it's unclear what size you want in the UPDATE condition. I've picked 1:

    create table iplog (
        [date] date not null,
        sip int not null,
        dip int not null,
        port int not null,
        size int not null
    )
    GO
    merge iplog as t
    using (SELECT '20120101' as [date] , 1 as sip , 2 as dip , 80 as port) as s
    on t.[date]=s.[date] and t.sip=s.sip and t.dip=s.dip and t.port=s.port
    when matched then
        update set t.size=t.size+1 --What should this be?
    when not matched then
        insert values ('20120101',1,2,80,1);
    
    select * from iplog
    

    You'll note that the source doesn't reference the target table at all now.


    Side note - I'd recommend avoiding SQL keywords such as date as column names.

提交回复
热议问题