两个数据库的表结构相同,但表名前缀不一样,现要保持原有的数据表的 ID 导过来不变。
用数据库批量导入/导出工具行不通,只能自己写SQL语句。奈何有180多个表,手工写肯定是累S个人。
我的解决办法:
先用 OpenDataSource 远程连接服务器,然后执行插入语句可行。其语句如下:
truncate table ActUser
SET IDENTITY_INSERT ActUser on
insert into ActUser(
[ID],[PassWord],[UserName]
) select
[ID],[PassWord],[UserName]
from opendatasource('SQLOLEDB','data source=DBSERVERIP;uid=sa;password=sa').TEST.dbo.ActUser
SET IDENTITY_INSERT ActUser off
SET IDENTITY_INSERT ActUser on
insert into ActUser(
[ID],[PassWord],[UserName]
) select
[ID],[PassWord],[UserName]
from opendatasource('SQLOLEDB','data source=DBSERVERIP;uid=sa;password=sa').TEST.dbo.ActUser
SET IDENTITY_INSERT ActUser off
然后我想到用游标结合 sysobjects 和 syscolumns 来实现自动生成这样的语句,其代码如下:
declare mycursor cursor
for
select [id],[name] from dbo.sysobjects where type='U'
open mycursor
declare @tablename sysname
declare @tableid sysname
fetch next from mycursor into @tableid , @tablename -- 获取表名
while(@@fetch_status=0)
begin
print '-- [' + @tablename + ']'
-- 拼凑字段,将行转为字符串 --
DECLARE @fields varchar(8000)
set @fields = ''
SELECT @fields = '' + @fields + '],[' + name FROM syscolumns WHERE id=object_id(@tablename) ORDER BY colid
set @fields = '[' + STUFF(@fields, 1, 3, '') + ']'
-- 拼凑字段 End --
--print @fields
/******* 避免因字段过长而导致截断情形 ********/
print 'truncate table ' + @tablename --清理数据
print 'SET IDENTITY_INSERT '+ @tablename +' on ' --可使自增长列转为可插入数据,不用重新生成 ID
print 'insert into ' + @tablename + '('
print @fields
print ') select '
print @fields
print ' from opendatasource('
+ '''SQLOLEDB'',''data source=DBServerIP;uid=sa;password=sa'').TEST.dbo.'
+ replace(@tablename ,'Wait_', 'Has_')
print 'SET IDENTITY_INSERT '+ @tablename +' off '
print char(13) -- 换行
fetch next from mycursor into @tableid , @tablename
end
close mycursor
deallocate mycursor
for
select [id],[name] from dbo.sysobjects where type='U'
open mycursor
declare @tablename sysname
declare @tableid sysname
fetch next from mycursor into @tableid , @tablename -- 获取表名
while(@@fetch_status=0)
begin
print '-- [' + @tablename + ']'
-- 拼凑字段,将行转为字符串 --
DECLARE @fields varchar(8000)
set @fields = ''
SELECT @fields = '' + @fields + '],[' + name FROM syscolumns WHERE id=object_id(@tablename) ORDER BY colid
set @fields = '[' + STUFF(@fields, 1, 3, '') + ']'
-- 拼凑字段 End --
--print @fields
/******* 避免因字段过长而导致截断情形 ********/
print 'truncate table ' + @tablename --清理数据
print 'SET IDENTITY_INSERT '+ @tablename +' on ' --可使自增长列转为可插入数据,不用重新生成 ID
print 'insert into ' + @tablename + '('
print @fields
print ') select '
print @fields
print ' from opendatasource('
+ '''SQLOLEDB'',''data source=DBServerIP;uid=sa;password=sa'').TEST.dbo.'
+ replace(@tablename ,'Wait_', 'Has_')
print 'SET IDENTITY_INSERT '+ @tablename +' off '
print char(13) -- 换行
fetch next from mycursor into @tableid , @tablename
end
close mycursor
deallocate mycursor
将生成的 SQL 语句放到查询分析器里执行一下,生成SQL 语句,然后执行一下,OK,完工。