Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

SQL cursor variable not working

$
0
0

My cursor variable @ProductNumber is not working if used in dynamic statement?

It says "Must declare scalar variable". But this is a cursor variable. But when I used it not dynamic, it works.

Please help. Thanks.

DECLARE@TargetDB NVARCHAR(50)DECLARE@SourceDB NVARCHAR(50)DECLARE@DateEffectiveFrom datetimeDECLARE@InsertRecords NVARCHAR(1000)SET@TargetDB ='MySSISDb'SET@SourceDB ='MySSISDb2'SET@DateEffectiveFrom ='2013-12-29'Declare@ProductNumber INT;DECLARE@SqlDb NVARCHAR(Max)DECLARE Cur1 CURSORFORSELECT CAST(@SqlDb AS NVARCHAR(MAX))SET@SqlDb ='SELECT ProductNumber From '+@SourceDB+'.dbo.Item (NOLOCK) WHERE NOT EXISTS (SELECT 1 FROM '+@TargetDB+'.dbo.Item2 WHERE ProductNumber = '+@SourceDB+'.dbo.Item.ProductNumber)'EXEC sp_executesql @SqlDbOPEN Cur1FETCH NEXT FROM Cur1 INTO@ProductNumber;WHILE@@FETCH_STATUS =0BEGINSET@InsertRecords ='INSERT INTO '+@TargetDB +'.dbo.Item2( ProductNumber, ProductName, ListPrice, BirthDate) SELECT ProductNumber, ProductName, ListPrice, '''+CONVERT(nvarchar(25),@DateEffectiveFrom,120)+''' FROM '+@SourceDB +'.dbo.Item WHERE '+@SourceDB +'.dbo.Item.ProductNumber = @ProductNumber'--WHERE ' + @SourceDB + '.dbo.Item.ProductNumber = @ProductNumber --(this is where the problem)EXEC sp_executesql @InsertRecordsFETCH NEXT FROM Cur1 INTO@ProductNumber;ENDCLOSE Cur1;DEALLOCATE Cur1;


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>