SQL使用执行为光标的字符串



我想使用一个变量我传递给存储过程,以在我的查询中用作表名,以便在光标中用于发送电子邮件。我的摘要样本如下:

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

问题是为什么我会出现错误的原因:

错误的语法

使用字符串查询后,在光标中使用字符串查询时使用什么?

是:

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

OPEN getemail

for语句之后的语法不正确。

请找到此链接的语法和更多信息链接。

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

还是可能是问题您忘了评论您的声明光标,该光标

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

,或者您可以使用动态SQL创建查询

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

如果这不起作用,请发布您的整个查询,以获取确切的情况。

相关内容

最新更新