我有一个表Order
,我希望按clientId
删除数据。该表每个客户端有超过2071458条记录。而且这个表有16个表的外键引用。禾当我尝试通过clientid删除记录时,删除reocord需要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
答案 0 :(得分:4)
您可以移除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)