我有以下问题:
DELETE FROM [Entry]
WHERE CompanyId = 1
AND EmployeeId IN (3, 4, 6, 7, 14, 17, 20, 21, 22,....100 more)
AND Entry_Date = '2016-12-01'
AND Entry_Method = 'I'
DELETE FROM [WrongEntry]
WHERE CompanyId = 1
AND EmployeeId IN (4, 7, 14, 17, 20, 21, 22, 24....100 more)
AND Entry_Date = '2016-12-01'
AND Entry_Method = 'I'
DELETE FROM [Entry]
WHERE CompanyId = 1
AND EmployeeId IN (1, 4, 6, 7, 14, 17, 20, 21, 22,....100 more)
AND Entry_Date = '2016-12-02'
AND Entry_Method = 'I'
DELETE FROM [WrongEntry]
WHERE CompanyId = 1
AND EmployeeId IN (5, 7, 14, 17, 20, 21, 22, 24....100 more)
AND Entry_Date = '2016-12-02'
AND Entry_Method = 'I'
就像我在2016年12月1日至2016年12月31日期间的整个月一样。
当我运行这些查询时,需要花费大量时间和时间。同时,在执行这些查询时,表会被锁定一段时间,直到执行完成。
在上述方案中批量删除的最佳方法是什么?还有其他方法吗?如何快速批量删除这些查询?
注意:EmployeeId
始终不同
答案 0 :(得分:2)
也许使用不平等会做你想要的:
DELETE FROM [Entry]
WHERE CompanyId=1 AND
EmployeeId IN (3,4,6,7,14,17,20,21,22,....100 more) AND
Entry_Date >= '2016-12-01' AND
Entry_Date < '2017-01-01' AND
Entry_Method = 'I';
答案 1 :(得分:2)
您可以更改查询以查找日期范围而不是特定日期。
试试这个。
DELETE FROM [Entry] WHERE CompanyId=1 AND EmployeeId IN(3,4,6,7,14,17,20,21,22,....100 more)
AND Entry_Date >= '2016-12-01' AND Entry_Date <= '2016-12-31'
AND Entry_Method = 'I'
DELETE FROM [WrongEntry] WHERE CompanyId=1 AND EmployeeId IN(4,7,14,17,20,21,22,24....100 more)
AND Entry_Date >= '2016-12-01' AND Entry_Date <= '2016-12-31'
AND Entry_Method = 'I'
请注意,根据您的字段数据类型,您可能需要将字符串转换为查询中的日期。
答案 2 :(得分:0)
我的第一个建议是将列表放入临时表或表变量,这是EmployeeId =&gt; tempEmployees。第二个是应用块删除,这种技术非常有效,你可以避免与锁相关的问题,这里有一个示例:
https://sqlperformance.com/2013/03/io-subsystem/chunk-deletes
简单来说:
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r > 0
BEGIN
BEGIN TRANSACTION;
DELETE TOP (5000) FROM TableToDelete;
SET @r = @@ROWCOUNT;
COMMIT TRANSACTION;
END