One of my clients has two Head Offices. Each HO has almost 300 workstation and my client doesn't want to replicate all the info into one HO, so he asked if i can get some info into secondary tables with jobs from HO no. 2 to HO no. 1 for some reports... This part is done and i had no issue but the real problem appeared when i had to modify the stored procedure for the reports.
Before i had the code like this:
SELECT D.IdDocument, D.etc...
FROM Document D (NOLOCK)
JOIN OtherTable OT (NOLOCK) on etc...
Now i've tried it like this:
1) First attempt:
SELECT DXD.IdDocument, DXD.etc...
FROM
(
SELECT D.*
FROM Document D (NOLOCK)
UNION ALL
SELECT D2.*
FROM RemoteDocument D2 (NOLOCK)
) DXD
JOIN OtherTable OT on etc...
2) Second attempt:
CREATE TABLE #TempDocument
(
IdDocument INT,
IdLocation INT,
etc..
)
CREATE INDEX IDX_TMP_Document ON #TempDocument (IdDocument, IdLocation)
INSERT INTO #TempDocument
SELECT DXD.*
FROM
(
SELECT D.*
FROM Document D (NOLOCK)
UNION ALL
SELECT D2.*
FROM RemoteDocument D2 (NOLOCK)
) DXD
SELECT DXD.IdDocument, DXD.etc...
FROM #TempDocument DXD
JOIN OtherTable OT (NOLOCK) on etc...
The problem is that before the sp ran in 5-10 minutes and now 30-40 minutes, the main issue that execution plan detected is in the union/insert using the union...
Can someone tell me a better/faster way to concatenate the info before using it?