Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the results of a stored procedure into a cursor within another stored procedure in SQL

I'm trying to put the results of a stored procedure into a cursor to use within the current procedure. I've added my code below but I'm not sure if this is possible or if my syntax is correct?

DECLARE cursorIDList CURSOR FOR
    EXEC spGetUserIDs
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID

I receive the following error: Incorrect syntax near 'EXEC'. Expecting SELECT, '(' or WITH.

Thanks in advance.

like image 207
Sun Avatar asked Jul 05 '12 10:07

Sun


People also ask

How to select from stored procedure with parameters in SQL Server?

SQL Server select from stored procedure with parameters 1 First, create a stored procedure that uses multiple parameters to execute some task and return the result. 2 Next, store the result returned by a stored procedure in a table variable. 3 In the end, use the SELECT statement to fetch some data from the table variable. More ...

How to convert a stored procedure into a table value function?

You could drop the results from the stored proc into a temp table and select from that for your cursor. Another option may be to convert your stored procedure into a table valued function. You use INSERT ... EXEC to push the result of the procedure into a table (can be a temp #table or a @table variable), the you open the cursor over this table.

How do I copy a stored procedure to a different table?

Copying a SQL Server Stored Procedure’s Results Set to a Local Temp Table You can copy the results set from a stored procedure to a local temp table in a three-step process. In the first step, create a fresh copy of the stored procedure with a select statement that generates a results set whose output you want to persist.

Is cursor supported in SQL Server stored procedures?

Need Help? Our Support Team is here to help. Here Mudassar Ahmed Khan has provided a tutorial with simple example that explains how to use Cursor in SQL Server Stored Procedures. Cursor is supported in all SQL Server versions i.e. 2000, 2005, 2008, 2008R2, 2012 and 2014.


1 Answers

You can do it like this:

DECLARE @t TABLE (ID INT)
INSERT INTO @t
EXEC spGetUserIDs

DECLARE cursorIDList CURSOR FOR
    SELECT * FROM @t
OPEN cursorIDList

FETCH NEXT FROM cursorIDList INTO @ID
like image 98
Ivan Golović Avatar answered Oct 16 '22 16:10

Ivan Golović