Solved

Store Procedure - Loop through data

Posted on 2009-07-10
3
249 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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
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.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

747 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

13 Experts available now in Live!

Get 1:1 Help Now