Does an update trigger an INSERT event as all updates are DELETE + (re)INSERT in SQL Server

前端 未结 2 1333
天命终不由人
天命终不由人 2021-01-16 12:53

As I understand it, when you update one or more rows in SQL Server, the record is deleted and reinserted with the new values. Does this therefore mean that an INSERT event

2条回答
  •  醉话见心
    2021-01-16 13:51

    An update never triggers an insert event even if physically it is implemented as an insert/delete as logically the operation is still an UPDATE.

    There is a phrase in the accepted answer that is not quite true if taken to be talking about logical updates of the key column.

    For updates that change the key values, SQL will not do those as in-place updates

    This is not the case for a multirow update against a unique index. For those SQL Server gives a plan with split/sort/collapse operators. So in the following example the 9 update operations get converted to 1 delete, 8 updates, and an insert.

    CREATE TABLE TestingUpdate7 (
    ID INT,
    SomeString CHAR(50)
    )
    
    CREATE UNIQUE CLUSTERED INDEX idx_ID ON TestingUpdate7 (ID)
    
    INSERT INTO TestingUpdate7 (ID, SomeString)
    VALUES
    (1,'One'),(2,'Two'),(3,'Three'),(4,'Four'),
    (5,'Five'),(6,'Six'),(7,'Seven'),(8,'Eight'),(9,'Nine')
    
    CHECKPOINT -- truncate the log, DB is in simple recovery.
    
    UPDATE TestingUpdate7
    SET  ID +=1
    
    SELECT Operation, Context, AllocUnitName 
    FROM fn_dblog(NULL, NULL) 
    

    Returns

    +-----------------+--------------------+---------------------------+
    |    Operation    |      Context       |       AllocUnitName       |
    +-----------------+--------------------+---------------------------+
    | LOP_BEGIN_CKPT  | LCX_NULL           | NULL                      |
    | LOP_XACT_CKPT   | LCX_BOOT_PAGE_CKPT | NULL                      |
    | LOP_END_CKPT    | LCX_NULL           | NULL                      |
    | LOP_BEGIN_XACT  | LCX_NULL           | NULL                      |
    | LOP_DELETE_ROWS | LCX_MARK_AS_GHOST  | dbo.TestingUpdate7.idx_ID |
    | LOP_SET_BITS    | LCX_PFS            | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_MODIFY_ROW  | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_INSERT_ROWS | LCX_CLUSTERED      | dbo.TestingUpdate7.idx_ID |
    | LOP_COMMIT_XACT | LCX_NULL           | NULL                      |
    +-----------------+--------------------+---------------------------+
    

提交回复
热议问题