Create Script :
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]
Now I am going to update the table as following : [just a dummy query may be return nothing]
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
I just want to know the update sequence. Does it always works from the last or there exists other conditions to be considered ?