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

时间:2015-03-04 07:59:39

标签: sql-server sql-server-2008 linked-server

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

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

1 个答案:

答案 0 :(得分:1)

您应该将动态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