我是刚加入IT部门的新生。我被要求调整需要更多时间的SP。
我遇到了一个花费更多时间的SP,发现一条特定的DELETE语句花费了更多时间。 该表包含数十亿条记录,每当运行SP时,其中数十亿条记录都需要删除。表具有包含SHOT_DATE列的聚集索引。该声明如下。请提供一些建议。
DELETE FROM TBL_STUDENT WHERE SHOT_DATE <= @YEAR AND
SHOT_DATE <> EOMONTH(SHOT_DATE)
答案 0 :(得分:0)
还有一些最佳做法
由于表中有数十亿行,因此最好总是批量删除(从小到大),以防止阻塞或日志文件增长
伪代码
DECLARE @startDate DATE @endDate DATE, @batchSize INT
SELECT @startDATE = Date1 --set them however you wish
SELECT @endDate = Date2
While there's data still --either use SELECT COUNT(1) OR WHILE EXIST (...)
DELETE TOP(@batchSize) FROM TBL_STUDENT WHERE SHOT_DATE BETWEEN @Date1 AND @Date2
--Sometimes I add a WAITFOR to have a break between delete, so other sessions can use the table
另一个代码
DECLARE @Criteria DATETIME
,@RowCount INT
SELECT @Criteria = GETDATE() - 60
,@RowCount = 10000
WHILE @RowCount = 10000
BEGIN
DELETE TOP (10000)
FROM ExampleTable
WHERE DateTimeCol < @Criteria
SELECT @RowCount = @@ROWCOUNT
END