经常遇到这种情况:需要获得整个远程服务器上的SQLServer数据库,但是没有权限导出数据,而使用脚本生成的方法总有这样那样的问题,并且速度超慢。这两天查找了有关的工具,发现BCP 命令行工具适合大量导入导出,BULK INSERT (SQLServer2005之后支持)命令适合带有自动增长列的表数据导入。
首先要生成数据库的脚本,在本地建立数据库,这个了解SQL Server的基本上都知道。
然后使用下列脚本进行数据的复制了。
1
DECLARE @remoteServerNameOrIP VARCHAR(50); --远程服务器名称或IP2
SET @remoteServerNameOrIP = '205.100.100.100';3
DECLARE @remoteServerUserName VARCHAR(50); --远程服务器用户名4
SET @remoteServerUserName = 'user';5
DECLARE @remoteServerPassword VARCHAR(50); --远程服务器密码6
SET @remoteServerPassword = '123';7
DECLARE @remoteServerDatabaseName VARCHAR(50); --远程数据库名8
SET @remoteServerDatabaseName = 'global';9
DECLARE @localServerNameOrIP VARCHAR(50); --本地服务器名称或IP10
SET @localServerNameOrIP = '127.0.0.1';11
DECLARE @localServerDatabaseName VARCHAR(50); --本地数据库名12
SET @localServerDatabaseName = 'global';13
DECLARE @tableName VARCHAR(50); --远程\本地数据库中表名14
DECLARE @fileDir VARCHAR(50); --导出\导入文件目录15
SET @fileDir = 'D:\global\';16
DECLARE @isSimple bit; --是否单表17
SET @isSimple = 1;18
DECLARE @simpleTableName VARCHAR(50); 19
SET @simpleTableName = 'NewsImages';20

21
exec('declare #tb cursor for select name from '+@localServerDatabaseName+'..sysobjects where xtype=''U''')22
open #tb23
fetch next from #tb into @tableName24
while @@fetch_status=025
begin26
--查看表数目27
EXEC('SELECT '''+@tableName+''', COUNT(*) FROM '+@localServerDatabaseName+'.dbo.'+@tableName);28
IF (@isSimple=0 OR (@isSimple=1 AND @tableName=@simpleTableName))29
BEGIN30

31
--导出远程数据库表数据到本地文件32
DECLARE @bcp VARCHAR(500);33
SET @bcp = 'BCP "'+@remoteServerDatabaseName+'.dbo.'+@tableName+'" out "'+@fileDir+@tableName+'.txt" -w -S"'+@remoteServerNameOrIP+'" -U"'+@remoteServerUserName+'" -P"'+@remoteServerPassword+'"';34
--EXEC master..xp_cmdshell @bcp;35

36
--导入数据文件到本地数据库37
DECLARE @bulk VARCHAR(500); 38
SET @bulk = 'BULK INSERT '+@localServerDatabaseName+'.dbo.'+@tableName+' FROM "'+@fileDir+@tableName+'.txt" 39
WITH(40
CHECK_CONSTRAINTS,41
DATAFILETYPE = ''widechar'',42
KEEPIDENTITY,43
KEEPNULLS,44
MAXERRORS = 1000,45
46
ERRORFILE = '''+@fileDir+@tableName+'_err.txt''47
)';48
--EXEC(@bulk);49
END50
fetch next from #tb into @tableName51
end52
close #tb53
deallocate #tb
浙公网安备 33010602011771号