Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Slow Update cursor

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2001-12-21 : 09:40:06
Tim D writes "I'm running SQLServer 2000 on a Win2K Server box.

I have two tables: Invoice and ExchangeRate
I want to store the exchange rate on the Invoice itself, by finding the corresponding exchange rate for the Invoice date. There are two problems here:
1. The only link between Invoice and ExchangeRate is WHERE
LEFT(CONVERT(varchar, Invoice.dOrdered, 101), 10) = LEFT(CONVERT(varchar, Exchange.dDate, 101), 10)
2. There are missing exchange rate entries (for weekends)

This was my first approach, but it ran for over an hour before I killed it in frustration. btw, there are 300,000 invoices.


declare @cur cursor
declare @date smalldatetime
declare @rate real

set @cur = cursor

for select distinct LEFT(CONVERT(varchar, dOrdered, 101), 10) as dOrdered from Invoice
where dordered is not null
open @cur
fetch next from @cur into @date
while @@fetch_status = 0
begin
-- using top 1 to get the nearest exchange rate if there wasn't an entry on that date
select TOP 1 ddate, rCADExchange from tblCADExchange
where left(convert(varchar, dDate, 101), 10) <= @date
order by ddate desc


update invoice set rCADExchange = @rate
where LEFT(CONVERT(varchar, dOrdered, 101), 10) = @date
and rCADExchange is null

fetch next from @cur into @date
end
close @cur
deallocate @cur
go


Any ideas on how to do this faster? Without a cursor maybe?"

izaltsman
A custom title

1139 Posts

Posted - 2001-12-21 : 10:33:12
This should be close:



UPDATE Invoice
SET Invoice.rCADExchange = exch.rCADExchange
FROM
tblCADExchange as exch
WHERE
CONVERT(varchar, exch.dDate,112) =
(SELECT MAX(dDate) FROM tblCADExchange AS a
HAVING MAX(CONVERT(varchar, a.dDate, 112))<=CONVERT(varchar, Invoice.dOrdered, 112))





Edited by - izaltsman on 12/21/2001 10:33:36
Go to Top of Page
   

- Advertisement -