0

I want to use a variable I pass to a stored procedure to be used as table name in my query to be used in cursor to be used to send email. My snippet sample is below:

--DECLARE @getemail CURSOR
--SET @getemail = CURSOR FOR
DECLARE @getemail CURSOR FOR 
SET @recipientquery =  'SELECT * FROM '+@tableA+''
EXEC sys.sp_executesql @recipientquery

Questions is why I am getting error in the for part saying:

Incorrect syntax

What is the correct syntax to use when using a string query after for in cursor?

2 Answers 2

1

It would be :

set @recipientquery = 'Declare  getemail CURSOR FOR SELECT * FROM'+@tableA

exec sp_executesql @recipientquery


OPEN getemail
Sign up to request clarification or add additional context in comments.

1 Comment

i see let me confirm ill be back here asap
0

You have incorrect syntax near after for statement.

Please find this link for syntax and more info link.

DECLARE vend_cursor CURSOR  
    FOR SELECT * FROM Purchasing.Vendor  
OPEN vend_cursor  
FETCH NEXT FROM vend_cursor;

Or may be this is the issue you forgot comment your declare cursor which is not used over there

--DECLARE @getemail CURSOR FOR    --- (here cursor for what...? )
SET @recipientquery =  'SELECT * FROM '+@tableA+''
EXEC sys.sp_executesql @recipientquery

Or you may use dynamic sql to create your query

Create table demotable  ( id int, name nvarchar(max) )

declare @tableA nvarchar(max)
set @tableA = 'demotable'

declare @recipientquery nvarchar(max)   
SET @recipientquery =  'DECLARE getemail CURSOR FOR  
                        SELECT * FROM '+@tableA+''
EXEC sys.sp_executesql @recipientquery
open getemail


close getemail
deallocate getemail

If this didn't work then please post your whole query, to get the exact scenario.

8 Comments

that is the whole query also you sample is different from my sample just by looking. I want to use a query string not a direct select query SET @recipientquery = 'SELECT * FROM '+@tableA+'' EXEC sys.sp_executesql @recipientquery
how you are getting this value of @tableA, cause if you are not selecting any row from table then there is no need to use cursor.cursor is use to iterate loop and there is no loop seen in your query.
I want to use a variable I pass to SP to be used as table name in my query to be used in cursor to be used to send email.
i need the cursor..your update does not solve my issue
then you need to apply cursor on calling this stored procedure, here you are passing just one @tableA directly, so no need to call cursor for that.
|

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.