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

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 How to declare a cursor for a dynamic SELECT ?

Author  Topic 

BruteWes
Starting Member

3 Posts

Posted - 2005-04-25 : 15:39:22
I need a cursor to select the top X of a table. However, I can't figure out how to declare it. I tried this but it does not work:

SELECT @sql = 'SELECT TOP ' + @NonRequiredQuestionCount + ' Q.QuestionID, Q.Question ' + 'FROM Training1_Question Q '

Declare NonRequiredQuestionCursor CURSOR FOR @sql


The select will be dynamic because of the top X syntax, but everything I read refers to using static SELECT statments for cursor declaration. Is this not possible? If not, what else can I do?

Thanks!

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2005-04-25 : 16:11:44
You could create a temp table, use dynamic SQL to insert the correct number of rows into the temp table, and then declare your cursor on the temp table.

Or, if the result set is not large without the TOP, you could just get out of your cursor loop after you have processed the number of rows you want.

CODO ERGO SUM
Go to Top of Page

BruteWes
Starting Member

3 Posts

Posted - 2005-04-25 : 16:17:48
Exiting out of the cursor after the top X records are processed is a great idea.

What is the syntax to break the loop?

Thanks!
Go to Top of Page

BruteWes
Starting Member

3 Posts

Posted - 2005-04-25 : 16:24:43
I found it, the BREAK command.

Works perfect, thank you!
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2005-04-25 : 16:59:55
[thud]

[/thud]

Ouch...

I got an idea!

Why don't you tell us what you're trying to accomplish instead.



Brett

8-)
Go to Top of Page

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2005-04-26 : 14:41:19
/me takes cursor out back and runs it over with his tractor for the rest of the day....
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2005-04-26 : 20:15:28
Make sure you get it on video Don, and upload it here.
Go to Top of Page

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2005-05-03 : 10:56:36
Ok, i strapped the Cursor onto the front of my dump truck. Here is a link to the video.

http://www.big-boys.com/articles/truckvswall.html
Go to Top of Page
   

- Advertisement -