我使用以下sql查詢來更新MyTable。代碼需要5到15分鐘。只要ROWS < = 100000000更新MyTabel,但當行數> 100000000時,需要指數時間更新MYTable。我如何更改此代碼以使用set-base而不是while循環?如何通過避免循環來優化這個t-sql腳本代碼?
DECLARE @startTime DATETIME
DECLARE @batchSize INT
DECLARE @iterationCount INT
DECLARE @i INT
DECLARE @from INT
DECLARE @to INT
SET @batchSize = 10000
SET @i = 0
SELECT @iterationCount = COUNT(*)/@batchSize
FROM MyTable
WHERE LitraID = 8175
AND id BETWEEN 100000000 AND 300000000
WHILE @i <= @iterationCount BEGIN
BEGIN TRANSACTION T
SET @startTime = GETDATE()
SET @from = @i * @batchSize
SET @to = (@i + 1) * @batchSize - 1
;WITH data
AS (
SELECT DoorsReleased, ROW_NUMBER() OVER (ORDER BY id) AS Row
FROM MyTable
WHERE LitraID = 8175
AND id BETWEEN 100000000 AND 300000000
)
UPDATE data
SET DoorsReleased = ~DoorsReleased
WHERE row BETWEEN @from AND @to
SET @i = @i + 1
COMMIT TRANSACTION T
END
編輯你的問題,並解釋你正在嘗試做什麼。 –
請爲您的數據庫和執行計劃提供一個恢復模型,用於單次迭代 – Devart
使用一些實際和索引列來計數批次而不是ROW_NUMBER處理。你爲什麼不使用'ID'本身? –