T-SQL 链接服务器的游标 INSERT SELECT

T-SQL cursor for linked server INSERT SELECT

我试图让这个游标循环工作,这样我就可以将数据从链接服务器复制到另一个服务器。但是,光标似乎处于循环中并且什么也不做。我究竟做错了什么?

    /* 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

您应该将动态 SQL 放在 WHILE 循环中。确保在内部调用 FETCH NEXT 以避免无限循环。

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'

OPEN @db
FETCH NEXT FROM @db INTO @tmp_key

WHILE(@@FETCH_STATUS = 0) BEGIN

    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';  

    EXEC sp_sqlexec @sql

    FETCH NEXT FROM @db INTO @tmp_key



END;

CLOSE  @db
DEALLOCATE @db