Solved

Store Procedure - Loop through data

Posted on 2009-07-10
3
250 Views
Last Modified: 2012-08-14
I have a very simple question regarding the SQL Server store procedure syntax.

I have a query that returns a set of data:
select myfield from mytable.

I want to execute that query and loop through the data set.

I tried:

declare
@results varchar(10)
select @results=myfield
from mytable

It fails obviously, because I expect over 100s of rows.

Could you post an example hot to accept a data set and loop through it ?

Thanks,
0
Comment
Question by:marper
  • 2
3 Comments
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 35 total points
ID: 24823377
declare @i int ,@results varchar(10)
DECLARE @Tab table ( i int identity , results varchar(10 ) )

INSERT Into @tab
select myfield
from mytable
SELECT @i = @@ROWCOUNT
WHILE @@ROWCOUNT  > 0
BEGIN
  SELECT @Result = result from @tab where i = @i
   --- do your stuff here

   set @i = @i -1
END

0
 
LVL 17

Assisted Solution

by:pssandhu
pssandhu earned 20 total points
ID: 24823447
You can use a cursor to loop through your record set as well:
Here is an example: http://www.mssqltips.com/tip.asp?tip=1599
Hope that helps.
P.
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 24824008
Never use a cursor use the table variable
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now