在SQL Server中更新序列

时间:2015-08-13 05:50:54

标签: sql-server

创建脚本:

CREATE TABLE [dbo].[tblTEST]
(
    [AccountNO] [varchar](10) NOT NULL,
    [Serial] [int] NOT NULL,
    [AccountType] [varchar](1) NOT NULL,
    [Due] [money] NOT NULL,
    [Balance] [money] NOT NULL,
    [Flag] [bit] NOT NULL,

    CONSTRAINT [PK_tblTEST] 
    PRIMARY KEY CLUSTERED ([AccountNO] ASC, [Serial] ASC)
          WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

现在我要更新表格如下:[只是虚拟查询可能不返回任何内容]

BEGIN TRAN

DECLARE @AccountNO VARCHAR(10), @AccountType VARCHAR(1), @Serial INT, @Balance AS MONEY, @PreBalance AS MONEY

UPDATE A
SET
        A.Balance = @Balance
        , @PreBalance = @Balance
        , @Balance = ( CASE WHEN @Balance IS NULL OR @AccountType <> A.AccountType
                            THEN A.Balance
                            ELSE @Balance - A.Due
                        END )
        , A.Flag = CASE WHEN @PreBalance = A.Balance THEN 0 ELSE 1 END
        , @AccountType = A.AccountType
FROM tblTEST A

SELECT * FROM tblTEST

ROLLBACK

我只是想知道更新顺序。它总是从最后一个起作用还是存在其他条件需要考虑?

1 个答案:

答案 0 :(得分:1)

更新语句执行的步骤是

  1. 从表中检索并从左侧检索变量
  2. 从左侧网站
  3. 设置数据到表格

    因此更新语句的执行顺序如下 -

    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
    

    例如

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

    执行将是

    第1行第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
    

    第1行第2阶段

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

    第2行第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
    

    第2行第2阶段

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

    等等