First always create backup of table to be updated or deleted.
SELECT * INTO [dbo].[tblTable01_YYYYMMDD] FROM [dbo].[tblTable01] f WITH (NOLOCK)
SELECT COUNT(*) FROM [dbo].[tblTable01] f WITH (NOLOCK)
SELECT COUNT(*) FROM [dbo].[tblTable01_YYYYMMDD] f WITH (NOLOCK)
Batch update records in a database table.
PRINT 'Update records from tblTable01'
CREATE TABLE #TempUpdateTable01
(
Id BIGINT IDENTITY (1,1) PRIMARY KEY,
TableId bigint
)
INSERT INTO #TempUpdateTable01
(
TableId
)
SELECT
f.TableId
FROM
[dbo].[tblTable01] f WITH (NOLOCK)
WHERE
f.Column01 = 123
DECLARE @start BIGINT,
@end BIGINT,
@min BIGINT,
@max BIGINT,
@inc INT = 10000
SELECT @min = 0, @max = MAX(Id)
FROM #TempUpdateTable01
WHILE @min < @max
BEGIN
BEGIN TRANSACTION
IF (@min + @inc) >= @max
BEGIN
SET @start = @min + 1
SET @end = @max
END
ELSE
BEGIN
SET @start = @min + 1
SET @end = @min + @inc
END
UPDATE
f
SET
f.Column02 = 'new'
FROM
[dbo].[tblTable01] f
INNER JOIN #TempUpdateTable01 t ON f.biTableId = t.TableId
WHERE
t.id BETWEEN @start AND @end
PRINT 'Id: ' + CAST(@start AS VARCHAR(50)) + ' to ' + CAST(@end AS VARCHAR(50))
COMMIT TRANSACTION;
SELECT @min = @min + @inc;
END;
DROP TABLE #TempUpdateTable01
Batch delete records in a database table.
PRINT 'Delete records from tbTable01'
CREATE TABLE #Temp_tbTable01
(
Id BIGINT IDENTITY (1,1) PRIMARY KEY,
TableId bigint
)
INSERT INTO #Temp_tbTable01
(
TableId
)
SELECT
pl.MyTableID
FROM
tbTable01 pl with(nolock)
left outer join tbTable02 fp with(nolock) on fp.PlateID = pl.PlateID
WHERE pl.Deleted = 1
AND fp.PlateID is null
-- 1,394,216
-- SELECT COUNT(*) FROM #Temp_tbTable01
DECLARE @start BIGINT,
@end BIGINT,
@min BIGINT,
@max BIGINT,
@inc INT = 10000
SELECT @min = 0, @max = MAX(Id)
FROM #Temp_tbTable01
WHILE @min < @max
BEGIN
BEGIN TRANSACTION
IF (@min + @inc) >= @max
BEGIN
SET @start = @min + 1
SET @end = @max
END
ELSE
BEGIN
SET @start = @min + 1
SET @end = @min + @inc
END
DELETE
f
FROM
[dbo].[tbTable01] f
INNER JOIN #Temp_tbTable01 t ON f.MyTableID = t.TableId
WHERE
t.id BETWEEN @start AND @end
PRINT 'Id: ' + CAST(@start AS VARCHAR(50)) + ' to ' + CAST(@end AS VARCHAR(50))
COMMIT TRANSACTION;
SELECT @min = @min + @inc;
END;
DROP TABLE #Temp_tbTable01
Result
Should be able to see result as the query is still running.
(10000 rows affected)
Id: 1 to 10000
(10000 rows affected)
Id: 10001 to 20000
(10000 rows affected)
Id: 20001 to 30000
(10000 rows affected)
Id: 30001 to 40000
(10000 rows affected)
Id: 40001 to 50000
(10000 rows affected)
Id: 50001 to 60000
(10000 rows affected)
Id: 60001 to 70000
(10000 rows affected)
Id: 70001 to 80000
(10000 rows affected)
Id: 80001 to 90000
(10000 rows affected)
Id: 90001 to 100000
Comments