Update sequence in SQL Server

后端 未结 1 1066
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 17:29

Create Script :

CREATE TABLE [dbo].[tblTEST]
(
    [AccountNO] [varchar](10) NOT NULL,
    [Serial] [int] NOT NULL,
    [AccountType] [varchar](1) NOT NULL,
         


        
相关标签:
1条回答
  • 2021-01-15 17:50

    Steps of update statement execution is

    1. retrieval from table and variable assignment from left side
    2. set to data to table from the left site

    so the sequence of execution of your update statement will be as follows-

    A.Balance = @Balance --4
    , @PreBalance = @Balance --1
    , @Balance = ( CASE WHEN @Balance IS NULL OR @AccountType <> A.AccountType
                        THEN A.Balance
                        ELSE @Balance - A.Due
                    END ) --2
    , A.Flag = CASE WHEN @PreBalance = A.Balance THEN 0 ELSE 1 END --5
    , @AccountType = A.AccountType --3
    

    example

    AccountNO Serial AccountType Due       Balance   Flag 
    --------- ------ ----------- --------- --------- ---- 
    A1        1      1           1000.0000 2000.0000 0    
    A1        2      1           1000.0000 2000.0000 0   
    

    execution will be

    row 1 phase 1

    , @PreBalance = null --1
    , @Balance = ( CASE WHEN null IS NULL OR null <> A.AccountType
                        THEN A.Balance
                        ELSE null - A.Due
                    END )  --2
    , @AccountType = A.AccountType --3
    

    row 1 phase 2

    A.Balance = 2000 --4
    , A.Flag = CASE WHEN null = A.Balance THEN 0 ELSE 1 END --5
    

    row 2 phase 1

    , @PreBalance = 2000 --1
    , @Balance = ( CASE WHEN 2000 IS NULL OR 1 <> A.AccountType
                        THEN A.Balance
                        ELSE 2000 - A.Due
                    END ) --2
    , @AccountType = A.AccountType --3
    

    row 2 phase 2

    A.Balance = 1000 --4
    , A.Flag = CASE WHEN 2000 = 1000 THEN 0 ELSE 1 END --5
    

    so on

    0 讨论(0)
提交回复
热议问题