Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I improve the performance of this stored procedure?

Okay so I made some changes to a stored procedure that we have, and it now takes 3 hours to run (it used to only take 10 minutes before). I have a temp table called #tCustomersEmail. In it, is a column called OrderDate, which has a lot of null values in it. I want to replace those null values with data from another database on a different server. So here's what I have:

I create another temp table:

Create Table #tSouth
(
CustID char(10),
InvcDate nchar(10)
)

Which I populate with this data:

INSERT INTO #tSouth(CustID, InvcDate)
SELECT DISTINCT
      [CustID],
      max(InvcDate) as InvcDate
  FROM D3.SouthW.dbo.uc_InvoiceLine I
  where EXISTS (SELECT CustomerNumber FROM #tCustomersEmail H WHERE   I.CustID =  H.CustomerNumber) 
  group BY I.CustID

Then I take the data from #tSouth and update the OrderDate in the #tCustomersEmail table, as long as the CustomerNumber matches up, and the OrderDate is null:

UPDATE #tCustomersEmail  
SET OrderDate = InvcDate 
FROM #tCustomersEmail  
INNER JOIN #tSouth ON #tCustomersEmail.CustomerNumber = [#tSouth].CustID
where #tCustomersEmail.OrderDate IS null

Making those changes caused the stored procedure to take FOR-EV-ER (Sandlot reference!)

So what am I doing wrong?

BTW I create indexes on my temp tables after I create them like so:

create clustered index idx_Customers ON #tCustomersEmail(CustomerNumber)
CREATE clustered index idx_CustSouthW ON #tSouth(CustID)
like image 388
broke Avatar asked Feb 04 '26 12:02

broke


1 Answers

Try skipping the #tsouth table and use this query:

UPDATE a
SET OrderDate = (select max(InvcDate) from D3.SouthW.dbo.uc_InvoiceLine I 
                 where a.customernumber = custid)  
FROM #tCustomersEmail a  
WHERE orderdate is null

I don't think the index will help you in this example

like image 169
t-clausen.dk Avatar answered Feb 06 '26 05:02

t-clausen.dk