Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stored Procedure Help

Status
Not open for further replies.

faccorp

Programmer
Jan 24, 2002
58
US
Hi,

I currently have a stored procedure where I pass in the ID of a customer, and the stored procedure performs sum selects and updates a field in the same customer table. Like this;

Code:
CREATE PROCEDURE [dbo].[Balance]

(
	@cusid Integer
)

AS

UPDATE CUSTOMERS

SET BALANCE =

(SELECT SUM(Amount)
	FROM dbo.CUSTOMERS INNER JOIN
             dbo.Transactions ON dbo.CUSTOMERS.ID = dbo.Transactions.[Customer ID]
	WHERE (dbo.Transactions.[Customer ID] = @cusid))


WHERE ID = @cusid
GO

But what if I want the stored procedure to automatically fill the 'BALANCE' column for ALL the patients. I'm not sure how to efficiently 'loop' through all the customers and track the @cusid variable.

Thanks
 
UPDATE CUSTOMERS
SET BALANCE =
(SELECT SUM(Amount)
FROM dbo.Transactions WHERE dbo.CUSTOMERS.ID = dbo.Transactions.[Customer ID])



======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
Thanks,

But when I run this, each customer ends up getting the same balance written to the BALANCE column. And the Balance displayed is the total balance for ALL the customers. The BALANCE column should only show the balance for the specific customer.

Thanks Again
 
Check your typing.
Note that CUSTOMERS does not appear as a table in the subquery.


======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
Code:
CREATE TABLE #TEMP (Amount money, CUSTID int)
INSERT INTO #TEMP
SELECT SUM(Amount),[Customer ID]
FROM dbo.Transactions 
GROUP BY [Customer ID]
GO
UPDATE CUSTOMERS
SET BALANCE = Amount
FROM CUSTOMERS as C INNER JOIN #TEMP as T
ON C.ID = T.CUSTID
GO

[bandito] [blue]DBomrrsm[/blue] [bandito]
 
if you want to use a join rather than a correlated subquery then

UPDATE CUSTOMERS
SET BALANCE = Amount
FROM CUSTOMERS as C
INNER JOIN (SELECT Amount = SUM(Amount),CUSTID = [Customer ID]
FROM dbo.Transactions
GROUP BY [Customer ID])as T
ON C.ID = T.CUSTID


======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top