查询会话不再响应
Query Session no longer respond
我正在尝试执行以下 T-SQL 语句:
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRANSACTION
DECLARE @nRows INT = 1
DECLARE @DataCancellazione DATE = DATEADD(DAY, -7, GETDATE())
CREATE TABLE #IDToDel (ID BIGINT)
WHILE @nRows > 0
BEGIN
INSERT INTO #IDToDel
SELECT TOP 5000 LogID
FROM MioDB.Test
WHERE CAST(ReceivedDate AS date) < @DataCancellazione
SELECT @nRows = @@ROWCOUNT
DELETE RM WITH (PAGLOCK)
FROM MioDB.Test RM WITH (PAGLOCK)
INNER JOIN #IDToDel TBD ON RM.LogID = TBD.ID
TRUNCATE TABLE #IDToDel
END
ROLLBACK
当我启动执行时,查询 window 似乎不再响应,并且进程中的 CPUTime 和 DiskIO 没有特别增加。谁能帮帮我谢谢。
老实说,我认为你把问题复杂化了。 SQL 服务器可以 轻松地 一次处理数百万行,我怀疑您可能会在几个 100 万行的批次中完成此操作。如果您至少有 4,000,000 行要删除,那么 5,000 行将需要 800 次迭代。
也不需要临时的table,一个DELETE
可以利用一个TOP
,所以你每次循环删除那么多行就可以了。我用一个变量定义它,然后传递它(1,000,000 行)。这意味着所有内容都在 4 次迭代中被删除,而不是 800 次。您可能想稍微减小大小,但我建议 500,000 是一个简单的选择。
这为您提供了以下更简洁的批处理:
SET NOCOUNT ON;
--The following transaction level seems like a terrible idea when you're performing DDL statements. Don't, just don't.
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
DECLARE @BatchSize int = 1000000,
@DataCancellazione date = DATEADD(DAY, -7, GETDATE());
SELECT 1; --Dataset with 1 row
WHILE @@ROWCOUNT > 0
DELETE TOP (@BatchSize)
FROM MioDB.Test --A Schema called "MioDB" is a little confusing
WHERE ReceivedDate < @DataCancellazione; --Casting ReceivedDate would have had no change to the query
--And could well have slowed it down.
我正在尝试执行以下 T-SQL 语句:
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRANSACTION
DECLARE @nRows INT = 1
DECLARE @DataCancellazione DATE = DATEADD(DAY, -7, GETDATE())
CREATE TABLE #IDToDel (ID BIGINT)
WHILE @nRows > 0
BEGIN
INSERT INTO #IDToDel
SELECT TOP 5000 LogID
FROM MioDB.Test
WHERE CAST(ReceivedDate AS date) < @DataCancellazione
SELECT @nRows = @@ROWCOUNT
DELETE RM WITH (PAGLOCK)
FROM MioDB.Test RM WITH (PAGLOCK)
INNER JOIN #IDToDel TBD ON RM.LogID = TBD.ID
TRUNCATE TABLE #IDToDel
END
ROLLBACK
当我启动执行时,查询 window 似乎不再响应,并且进程中的 CPUTime 和 DiskIO 没有特别增加。谁能帮帮我谢谢。
老实说,我认为你把问题复杂化了。 SQL 服务器可以 轻松地 一次处理数百万行,我怀疑您可能会在几个 100 万行的批次中完成此操作。如果您至少有 4,000,000 行要删除,那么 5,000 行将需要 800 次迭代。
也不需要临时的table,一个DELETE
可以利用一个TOP
,所以你每次循环删除那么多行就可以了。我用一个变量定义它,然后传递它(1,000,000 行)。这意味着所有内容都在 4 次迭代中被删除,而不是 800 次。您可能想稍微减小大小,但我建议 500,000 是一个简单的选择。
这为您提供了以下更简洁的批处理:
SET NOCOUNT ON;
--The following transaction level seems like a terrible idea when you're performing DDL statements. Don't, just don't.
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
DECLARE @BatchSize int = 1000000,
@DataCancellazione date = DATEADD(DAY, -7, GETDATE());
SELECT 1; --Dataset with 1 row
WHILE @@ROWCOUNT > 0
DELETE TOP (@BatchSize)
FROM MioDB.Test --A Schema called "MioDB" is a little confusing
WHERE ReceivedDate < @DataCancellazione; --Casting ReceivedDate would have had no change to the query
--And could well have slowed it down.