使用链接服务器将大量表从一个数据库移动到另一个数据库

时间:2016-02-15 12:31:30

标签: sql sql-server

当时移动一个表是没问题的,我有查询,但我有更多的表需要提取几次,所以我想要一个脚本为我做了。< / p>

基本上这是我在sql中需要的代码,但不知道如何编写它。从数据库执行,他们应该最终进入。

for @TableName in ('TABLE1','TABLE2','TABLE3')

SELECT *
INTO SCHEMA.@TableName 
FROM 
OPENQUERY (LINKEDSERVER,'SELECT * FROM @TableName')

End 

2 个答案:

答案 0 :(得分:1)

您可以使用表格列表中的光标并循环显示。然后要添加更多表,只需将它们添加到list_of_tables:

declare @tablename nvarchar(128);
declare @sqlquery nvarchar(max);

declare d cursor for 
select tablename from (
select 'Table1' as tablename
union
select 'Table2' as tablename
union
select 'Table3' as tablename ) as list_of_tables;

open d;
    fetch next from d into @tablename;
    while @@fetch_status = 0
    begin
        set @sqlquery = 'SELECT * INTO SCHEMA.' + QUOTENAME(@TableName) + ' 
                    FROM 
                    OPENQUERY (LINKEDSERVER,''SELECT * FROM ' + QUOTENAME(@TableName)+ ''');'
        exec (@sqlquery);
        fetch next from d into @tablename;
    end;
close d;
deallocate d;

答案 1 :(得分:0)

您可以从sys.objects

生成脚本

如:

SELECT 
        'SELECT * 
         INTO Schema.' + SO.name + '
         FROM 
            OPENQUERY(LINKEDSERVER, ''SELECT * FROM ' + SO.name + ''')
         '
    FROM 
        OPENQUERY(LINKEDSERVER
                    , 'SELECT * FROM sys.objects WHERE type = ''U''') SO