MERGE Query and deleting records

前端 未结 4 1606
花落未央
花落未央 2021-01-01 09:02

I have a table that looks something like:

AccountID, ItemID
1, 100
1, 200
2, 300

I have a proc that accepts a table value parameter which u

4条回答
  •  既然无缘
    2021-01-01 09:47

    Hope this helps.

    --  myTable
    --  (
    --      GroundID bigint, -- FK
    --      GroupID, bigint, -- FK
    --      AcceptingReservations bit
    --  );
    
    merge into myTable as target
    using @tmpTable as source
        on  ( source.GroundID   = target.GroundID )
        and ( source.GroupID    = target.GroupID )
    when
        not matched by target
        then
            insert ( GroundID, GroupID, AcceptingReservations )
            values
            (
                source.GroundID,
                source.GroupID,
                source.AcceptingReservations
            )
    -- If there is a row that matches, update values;
    when matched
        then
            update set
                target.AcceptingReservations = source.AcceptingReservations
    -- If they do not match, delete for that GroundID only;
    when
        not matched by source
        and target.GroundID = @GroundID
            then
                delete;
    

提交回复
热议问题