0
set @SQL=N' select  @minTableId   = MIN(id)  from ' + @AcDB + '.dbo.vTblOfRollNo '

Declare Cursor For
EXEC SP_EXECUTESQL @SQL 

if i have declared all the variables in above query but Declaration of cursor in above query shows ERROR. What is Solution?

2
  • 2
    Are you sure you want a cursor? It is bad style to use cursors if you could do the same using ordinary SQL. Have you tried writing the query without cursors? Why is that not possible in your case? Commented Jan 2, 2010 at 10:41
  • 1
    Your SQL appears to only return one value anyway - what's the point of the cursor? Commented Jan 2, 2010 at 13:10

2 Answers 2

2

In order to execute a cursor over dynamic SQL you must put the output of your dynamic sql into a temporary table and then cursor over the temporary table like this:

DECLARE @TableName NVARCHAR(100)
DECLARE @SQL NVARCHAR(1000)
CREATE TABLE #TempTABLE(email NVARCHAR(200))

SET @TableName='Users'
SELECT @SQL='INSERT INTO #TempTable SELECT email FROM ' + @TableName 
EXEC (@SQL)

DECLARE MyCursor CURSOR FOR SELECT * FROM #TempTable
OPEN MyCursor
DECLARE @Email NVARCHAR(200)
FETCH NEXT FROM MyCursor INTO @Email

WHILE @@FETCH_STATUS = 0
BEGIN
 PRINT 'Email = ' + @Email
 FETCH NEXT FROM MyCursor INTO @Email
END

CLOSE MyCursor
DEALLOCATE MyCursor
DROP TABLE #TempTABLE
Sign up to request clarification or add additional context in comments.

Comments

0

I dont think you need a cursor for this

try

DECLARE @AcDB VARCHAR(10),
        @Sql NVARCHAR(MAX)

set @SQL=N' select MIN(id)  from ' + @AcDB + '.dbo.vTblOfRollNo '

DECLARE @Temp TABLE(
        MinID INT
)
INSERT INTO @Temp EXEC SP_EXECUTESQL @SQL 

DECLARE @minTableId INT
SELECT TOP 1 @minTableId = MinID FROM @Temp

SELECT @minTableId

EDIT: Also here is the actual CURSOR documentation

DECLARE CURSOR (Transact-SQL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.