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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping Through Items in a String

Status
Not open for further replies.

Kush

Programmer
Sep 20, 2000
24
0
0
US
I have a String which is a comma spearated list of values.
I now need to take each value from this string (while there are still values in the string) and use them in a query one by one. Essentially, I want to loop once for each value in the string. How can I do this?


Here's what I want to achieve...

set @my_string = 'john, lisa, matt, beth, stu'

for every item in @my_string
select *
from details
where name = (item in @my_string)

get next value...

I am not sure of the syntax...

I would appreciate any help.

Thanks a lot.


 
Rather than using a cursor try this:

select *
from details
where name in (@my_string)

That will get you all your results.

Hope this helps.
 
Just in case the previous example didn't make sense, I did this one against the Northwind database:


declare @my_string varchar(255)
declare @sqlstring varchar(255)
set @my_string = '4,5,6'

SELECT @SQLSTRING = 'select * from orders
where employeeid in (' + @my_string + ')'

exec (@SQLSTRING)



Hope this helps.
 
Thanks so much, MeanGreen!

:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top