如何提高查询性能以更快地删除子 table 记录

how to improve query performance to delete child table record faster

我有一个 table Order,我想通过 clientId 删除数据。 table 每个客户有超过 2071458 条记录。而这个 table 有外键引用 16 table 。哇,当我尝试通过 clientid 删除记录时,删除记录需要 2-4 小时。那么我怎样才能提高性能以更快地完成它。如果可以,我可以使用子查询吗?我如何在此查询中使用。下面是我正在使用的查询。

DECLARE @ORDERID int   
DECLARE DEL_RelDataOFOrdeTab CURSOR FOR  
SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID  
 OPEN DEL_RelDataOFOrdeTab  

  FETCH NEXT FROM DEL_RelDataOFOrdeTab  INTO @ORDERID  
   WHILE @@FETCH_STATUS = 0  

     BEGIN   
       DELETE FROM AUTHORIZED WHERE ORDERID = @ORDERID  
       DELETE FROM AUTODISPALERTS WHERE ORDERID = @ORDERID  
       DELETE FROM DRIVER_REIMBURSEMENT WHERE ORDERID = @ORDERID  
       DELETE FROM FAXPOD WHERE ORDERID = @ORDERID  
       DELETE FROM GENERICFIELDS WHERE ORDERID = @ORDERID  
       DELETE FROM [Messages] WHERE ORDERID = @ORDERID  
       DELETE FROM ORDAUDIT WHERE ORDERID = @ORDERID  
       DELETE FROM OrderNotification WHERE ORDERID = @ORDERID  
       DELETE FROM OrderNotificationActions WHERE ORDERID = @ORDERID  
       DELETE FROM ORDERSPAID WHERE ORDERID = @ORDERID  
       DELETE FROM ROUTESERVERORDERS WHERE ORDERID = @ORDERID  
       DELETE FROM UnfinalizedOrders WHERE ORDERID = @ORDERID  
       print 'DELETING FROM ORDE_'  
       DELETE FROM orde_ where ORDERID = @ORDERID  
       PRINT @ORDERID  
     FETCH NEXT FROM DEL_RelDataOFOrdeTab INTO @ORDERID  
     END  

CLOSE DEL_RelDataOFOrdeTab   
DEALLOCATE DEL_RelDataOFOrdeTab  

DELETE FROM orde_ WHERE CLIENTID = @ClientID   

您可以删除 CURSOR 并只使用 SUBQUERY

DELETE FROM AUTHORIZED WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM AUTODISPALERTS WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM DRIVER_REIMBURSEMENT WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM FAXPOD WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM GENERICFIELDS WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM [Messages] WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM ORDAUDIT WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM OrderNotification WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM OrderNotificationActions WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM ORDERSPAID WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM ROUTESERVERORDERS WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM UnfinalizedOrders WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)
DELETE FROM orde_ WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)

基本上,它取代了

中的WHERE子句
WHERE ORDERID = @ORDERID

WHERE ORDERID IN (SELECT ORDERID FROM orde_ WHERE CLIENTID = @ClientID)