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 2008 Forums
 Transact-SQL (2008)
 Select all from a Cursor??

Author  Topic 

chadbruels
Starting Member

2 Posts

Posted - 2011-10-24 : 11:46:55
Hello intelligent people!

I have a need to design a stored procedure that will either return a result set or loop through and process the desired records. I'd like to write and maintain my select statement for this purpose once. As such, I was hoping I could accomplish something like the following:

DECLARE RAD_CURSOR CURSOR FOR
SELECT * FROM AWESOME_TABLE

IF @IN_SWITCH = 1 BEGIN
-- Process records in a loop
END ELSE BEGIN
-- Select all records in the cursor
END

Documentation on cursors did not reveal any method to me for accomplishing this. I was speculating on using a parameter in the declare statement of the cursor but that has thus far not been successful with the syntax I have attempted. So something like this I've been trying:

DECLARE @TEXT NVARCHAR(MAX)
SET @TEXT = 'SELECT * FROM AWESOME_TABLE'

DECLARE RAD_CURSOR CURSOR FOR @TEXT
OPEN RAD_CURSOR

FETCH NEXT FROM RAD_CURSOR

WHILE etc, etc...END

CLOSE RAD_CURSOR
DEALLOCATE RAD_CURSOR

If anyone has toyed with this idea or can come up with a resolution such that I don't have to maintain two copies of the same select statement it would be greatly appreciated.

Thanks for your time!

-----
PC at work, Mac at home.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-24 : 11:52:25
why do you need cursor here? I feel like you can very well achieve your requirement using set based technique. the processing as well as display can be done set based.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -