SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Stored procedure: Dynamic loop? Loop with sort?
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Huligan
Yak Posting Veteran

USA
66 Posts

Posted - 06/08/2004 :  08:00:09  Show Profile  Reply with Quote
Hello. I need to create a stored procedure that (I think) needs a dynamic loop or a loop on all records with a sort. Here are the tables involved.

tblMilk
-------
MilkID - int
MilkCost - money
UserID - int

tblLogMilk
---------
LogMilkID - int
LogMilkCostTotal - money
LogMilkCostAvg - money
LogMilkDate - datetime
UserID - int

tblUser
-------
UserID - int

I need a stored procedure to grab all records (thousands) from tblMilk. I need to group together the records by UserID. For each group of records, I need to calculate a sum and average for MilkCost and save those values to tblLogMilk with the UserID.

I know how to do this in ASP, but I'm struggling with finding the syntax I need. In ASP, I would sort the records by UserID and loop through the records. Everytime the UserID changes, I would perform my calculations, save them to tblLogMilk and reset the variables used to total the values from tblMilk.

Is this the way it should be done in a stored procedure or is there a better way? Either way, I would appreciate some syntax suggestions. Thanks.

Huligan

mohdowais
Sheikh of Yak Knowledge

United Arab Emirates
1456 Posts

Posted - 06/08/2004 :  08:21:30  Show Profile  Visit mohdowais's Homepage  Reply with Quote
Do you have Books Online (the SQL Server User Manual)? Look up GROUP BY.

Your query would be similar to:

SELECT UserID, SUM(MilkCost), AVG(MilkCost) FROM tblMilk GROUP BY UserID

OS
Go to Top of Page

JimL
SQL Slinging Yak Ranger

USA
1535 Posts

Posted - 06/08/2004 :  08:23:21  Show Profile  Visit JimL's Homepage  Reply with Quote
No Loops Please

Delete
From dbo.tblLogMilk

Insert into dbo.tblLogMilk
(logUserid,logMilkID,logMilkCostTotal,logMilkCostAvg)

Select UserID as logUserid, milkid as logMilkID, Sum(Milkcost) As logMilkCostTotal, Avg(Milkcost) AS logMilkCostAvg
From dbo.tblmilk
Group By UserID, MilkID

Jim
Users <> Logic

Edited by - JimL on 06/08/2004 13:42:18
Go to Top of Page

Huligan
Yak Posting Veteran

USA
66 Posts

Posted - 06/13/2004 :  09:08:47  Show Profile  Reply with Quote
Thanks for the help Jim. The only problem I had was the INSERT statement kept creating errors. Then I saw you edited your post and the correction took care of my error. Thanks again.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000