I have the following query:
DECLARE @accountCard TABLE (
numUsu VARCHAR(10)
,quantity INT
)
/*Takes less than a minute*/
INSERT INTO @accountCard
SELECT a.numUsu
,count(*)
FROM tableB a
INNER JOIN tableA b ON b.numUsu = a.numUsu
GROUP BY a.numUsu
/*This one takes the time*/
INSERT INTO finalTable
SELECT tarjeta = 'FIXED'
,fieldA = c.fieldA
,fieldB = c.fieldB
,fieldC = convert(BIGINT, b.numUsu)
,fieldD = ''
,fieldE = ''
,fieldF = rtrim(fieldF)
,fieldG = rtrim(fieldG)
,fieldH
,fieldI
FROM @accountCard a
INNER JOIN tableB b ON a.numUsu = b.numUsu
INNER JOIN tableA c ON b.numUsu = c.numUsu
WHERE quantity = 1
tableB has 2.7 million registers, and tableA has 1.7 million. Both tables have non-clustered, non-unique indexes for the column with which I do the join. Currently the second INSERT is taking too long: we have left it running for over 2 days and it was still not finished.
I ran the Estimated Execution Plan feature in SQL Server and it returned that the most expensive process was Searching for Keys (Clustered) in tablaA, but using the primary key, which isn't numUsu.
What can I do to speed it up?
Update 1:
select session_id,
status,
command,
blocking_session_id,
wait_type,
wait_time,
last_wait_type,
wait_resource
from sys.dm_exec_requests r
where r.session_id >= 50
and r.session_id <> @@spid;
There's only one session running and the result is:
+------------+-----------+---------+---------------------+----------------+-----------+----------------+---------------+ | session_id | status | command | blocking_session_id | wait_type | wait_time | last_wait_type | wait_resource | +------------+-----------+---------+---------------------+----------------+-----------+----------------+---------------+ | 59 | suspended | INSERT | 0 | PAGEIOLATCH_SH | 0 | PAGEIOLATCH_SH | 5:1:2431256 | +------------+-----------+---------+---------------------+----------------+-----------+----------------+---------------+