2011-07-11 117 views
2

儘管在將它傳遞給sp_executesql時聲明瞭一個類型爲「cursor」的變量,但我得到錯誤「操作數類型衝突:nvarchar與遊標不兼容」。是否可以將遊標變量傳遞給sp_executesql?

declare CURSOR_TO_PASS cursor for... --a simple select statement 
--cursor opened, values obtained, etc... 
declare @item nvarchar(5); 
declare @seqno int; 
[email protected] and @seqno populated 
declare @sql nvarchar(400) = N'update MYTABLE set Survey' + cast(@seqno as nvarchar(2)) + N' = @itemvalue where current of @sc'; 
exec sp_executesql @sql, N'@itemvalue nvarchar(5), @sc cursor', @itemvalue = @item, @sc = CURSOR_TO_PASS; 

我不知道什麼是錯的,因爲我已經宣佈@sc作爲一個光標,CURSOR_TO_PASS是一個光標,這我指定調用sp_executesql的時候@sc。那麼,是否可以將光標傳遞給sp_executesql?

回答

3

發佈此消息後不久我就想出瞭解決方案。事實上可以傳遞一個遊標變量。只需要一箇中間步驟,您必須將光標指定給「遊標變量」,如下所示:http://msdn.microsoft.com/en-us/library/ms190028.aspx「遊標可以通過以下兩種方法之一與遊標變量關聯:」,兩者都需要初始值,基本遊標變量聲明,如「DECLARE @MyVariable CURSOR;」。

所以我添加這些行到我的代碼:

declare @cursorvariable cursor; 
set @cursorvariable = CURSOR_TO_PASS; 

然後,我改變@sc = CURSOR_TO_PASS@sc = @cursorvariable,它工作得很好。