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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

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

Yak Posting Veteran

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.

MilkID - int
MilkCost - money
UserID - int

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

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.


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

Go to Top of Page

SQL Slinging Yak Ranger

1537 Posts

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

From dbo.tblLogMilk

Insert into dbo.tblLogMilk

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

Users <> Logic

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

Yak Posting Veteran

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  
 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.03 seconds. Powered By: Snitz Forums 2000