2017-09-15 9 views
1

私は以前のレコードに基づいてフィールドを更新する必要がある約30M行のMS SQLテーブルを持っています。ここでは動作しますが、それは時間の信じられないほどの量を取っているアップデートは、次のとおりです。ここで30M行のSQLデータベーステーブルの更新

UPDATE AccountTransaction 
SET EndingBalance = (SELECT COALESCE(SUM(b.amount), 0) 
FROM AccountTransaction AS b 
WHERE b.AccountId = AccountTransaction.AccountId 
and b.Date <= AccountTransaction.Date 
and (b.Date != AccountTransaction.Date 
    or b.CreatedDate < AccountTransaction.CreatedDate)) 
+ Amount 

がいっぱいDDLです:

CREATE TABLE [dbo].[AccountTransaction](
    [AccountTransactionId] [uniqueidentifier] NOT NULL, 
    [AccountId] [uniqueidentifier] NOT NULL, 
    [Amount] [decimal](16, 2) NOT NULL, 
    [EndingBalance] [decimal](16, 2) NOT NULL, 
    [Date] [date] NOT NULL, 
    [CreatedDate] [datetime2](3) NOT NULL, 
CONSTRAINT [PkAccountTransaction] PRIMARY KEY CLUSTERED 
(
    [AccountTransactionId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

CREATE NONCLUSTERED INDEX [IxAccountTransaction_AccountId_Date_CreatedDate] ON [dbo].[AccountTransaction] 
(
    [AccountId] ASC, 
    [Date] ASC, 
    [CreatedDate] ASC 
) 
INCLUDE ([AccountTransactionId], 
    [Amount], 
    [EndingBalance]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
GO 

CREATE NONCLUSTERED INDEX [IxAccountTransaction_AccountId] ON [dbo].[AccountTransaction] 
(
    [AccountId] ASC 
) 
INCLUDE ([AccountTransactionId], 
    [Amount], 
    [EndingBalance], 
    [Date], 
    [CreatedDate]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
GO 
+0

クエリには、テーブル(またはエイリアス)の「AccountTransaction」はありません。 – joop

+0

30Mの行には何個の異なる 'Table1Id'がありますか? – SqlZim

+0

'table1'からの金額を合計し、' table1id'で結合されたサブクエリを使用して 'table1'を更新しています。' table1id'が一意で、同じ行のみを参照している場合はどうしてサブクエリを使用していますか?同じ行を参照している場合、 'b.createddate'は' table1.createddate'や 'b.date!= table1.date'よりどうすればよいでしょうか? – SqlZim

答えて

0

以下は、はるかに優れた性能が得られるはずですし、利用することができますIxAccountTransaction_AccountId_Date_CreatedDateインデックスの...

WITH 
    cte_Runningtotal AS (
    SELECT 
     at1.EndingBalance, 
     NewEB = SUM(at1.Amount) OVER (PARTITION BY at1.AccountId ORDER BY at1.[Date] ROWS UNBOUNDED PRECEDING) 
    FROM 
     dbo.AccountTransaction at1 
    ) 
UPDATE rt SET 
    rt.EndingBalance = rt.NewEB 
FROM 
    cte_Runningtotal rt; 
関連する問題