We help IT Professionals succeed at work.
Get Started

Looping through a result set in a SQL Server stored procedure

dentyne
dentyne asked
on
5,512 Views
Last Modified: 2008-01-09
I have a stored procedure in which I want to dynamically build a query string or order by clause and execute it.  The column names I want to select are stored in a table.  So in my stored procedure I wanted to do something like:

1.   Do a query against this lookup table and get a list of column names
2.   Loop through that list and build an order by clause.
3.   Append the order by clause to a select query, execute it, and return the result set.

I am not sure how to do this though.  In Oracle there was this cursor that allowed me to loop through the results of a select statement, but I can't figure out how to do it here and also not to return that result set.  Thanks.
Comment
Watch Question
Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009
Commented:
This problem has been solved!
Unlock 1 Answer and 7 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE