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.
| Author |
Topic |
|
AndrewA
Starting Member
8 Posts |
Posted - 2010-07-14 : 14:59:43
|
| I want to make this more stored procedure code more efficient. It does work, but it takes 5-6 seconds to run and I am sure it can be done quicker? This was posted at the end of a previous post but someone suggested re-posting under a new title as it is an UPDATE query not a DELETE query as per my original post. Hopefully someone has some suggestions.Regards,Andrew.--Insert relevant rows into temporary tableselect id, WeekUID, WeeklyTotal into #tempAccounts from tblAccounts where LastEntryOfWeek = 1declare @MaxID intdeclare @Total numeric(10,2)declare @Counter intdeclare @ID intdeclare @UID varchar(15)--Loop through the temporary table one row at a time, calculating the weekly total figures--then update the temp table accordinglyset @Counter = 1select @MaxID = max(ID) from #tempAccountswhile @Counter <= @MaxID beginselect @ID = (select ID from #tempAccounts (nolock) where ID = @Counter)select @UID = (select WeekUID from #tempAccounts (nolock) where ID = @Counter)select @Total = (select SUM(Amount) from tblAccounts where WeekUID = @UID)update #tempAccounts set WeeklyTotal = @Total where ID = @Counterset @Counter = @Counter + 1;end--Update the live table with the data from the temp tableupdate tblAccountsset WeeklyTotal = #tempAccounts.WeeklyTotalfrom #tempAccountswhere tblAccounts.ID = #tempAccounts.ID--Dispose of the temp tabledrop table #tempAccountsThis is what I have so far. It updates the right entries but inserts the total for the entire database rather than the sub total for the block of records that share a unique week id (WeekUID):UPDATE fSET f.WeeklyTotal = (select SUM(Amount) from tblAccounts where WeekUID = WeekUID)FROM (SELECT ROW_NUMBER() OVER (PARTITION BY [weekUID] ORDER BY [datePaid] DESC) AS [rowPos],WeeklyTotal, WeekUID, AmountFROM tblAccounts) AS fWHERE [rowPos] = 1 |
|
|
|
|
|