I'm trying to get this cursor loop to work, so I could copy data from linked server to another server. However it seems that the cursor is in a loop and does nothing. What am I doing wrong?
/* For testing purposes I'm fetching data from
1 company only. The result should be one row.*/
DECLARE @tmp_key VARCHAR(14)
DECLARE @db cursor
DECLARE @sql NVARCHAR(MAX)
SET @db = CURSOR FOR
SELECT [CompanyId] FROM [Test].[dbo].[Company] WHERE [CompanyId] = '0001'
SET @sql = N'INSERT INTO [Stagingarea].[dbo].[Cominfo]
SELECT
convert(nvarchar(100),[Nro])
,convert(nvarchar(100),'+@tmp_key+' )
FROM [Linked_server_name].TK'+@tmp_key+'.[dbo].[cominfo]
where [rule1] <> 0 and acc = 1777';
OPEN @db
FETCH NEXT FROM @db INTO @tmp_key
while (@@fetch_status = 0)
begin
EXEC sp_sqlexec @sql
end;
CLOSE @db
DEALLOCATE @db