数据迁移

        数据迁移,就是从一个数据库中把需要的数据迁移到另一个数据库中。在迁移的过程中,如果两个数据库的数据结构是一致的,那就比较容易迁移。如果是不一致的,就要做相应的处理工作。在迁移的过程中,要充分利用可以利用的方法。建立视图,建立函数,字符串处理函数,这些都是经常用到的。下面通过两个例子说明。

         现有数据库test1,test2;test1有表Person(ID,Name,Sex),test2有表Emploee(ID,EmpleeName,Sex,Department).

         1.例子(1),把Person的数据迁移到Emploee去,sql:

----把Person的数据迁移到Emploee
----在test1运行此脚本
insert into [test2].[dbo].Emploee
([ID],[EmploeeName],[Sex],[Department])
select ID,Name,Sex,null
from Person

         2. 在这个例子中,我们吧Person的数据完全不变的全部迁移到了Emploee.有时候ID是主键,但不一定是Guid格式,它在表Person是唯一的,但迁移到Emploee时可能会和里面的ID重复。这时候,我们要重新给ID赋值。用到了数据库的newid()函数,例子(2)sql:

----把Person的数据迁移到Emploee
----在test1运行此脚本
insert into [test2].[dbo].Emploee
([ID],[EmploeeName],[Sex],[Department])
select newid(),Name,Sex,null
from Person

          3.如果两个表格数据不一致,如Person表的Sex存储的是“男”,“女”,对应Emploee表存的是“1”,“0”。这时后我们可以建立函数转换。例子(3)sql:

 ----在test1建立函数getSex
create function getSex(@type nvarchar(20))
returns varchar(1)
begin
declare @returntype varchar(1)
if(@type='男')  ---------把‘男’转换成‘1’
set  @returntype='1'
if(@type='女')  ---------把‘女’转换成‘0’
set @returntype='0'
return @returntype
end

 

----把Person的数据迁移到Emploee
----在test1运行此脚本
insert into [test2].[dbo].Emploee
([ID],[EmploeeName],[Sex],[Department])
select newid(),Name,dbo.getSex(Sex),null
from Person

         4.如果导入多个表存在主外键情况,先到主表,后导字表,如果数据迁移时主键可以直接迁移到新表则比较好办,如果不能,则要建立个临时字段记录原主键,以便和子表关联。

            在test1建立表PersonSchool(ID,PersonID,SchoolName,SchoolAddress);

            在test2建立表EmploeeSchool(ID,EmploeeID,SchoolName,SchoolAddress);

            把test1中Person,PersonSchool表中的数据分别迁移到Emploee,EmploeeSchool中,sql:

----建立临时列OldID保存ID
alter table [test2].[dbo].Emploee add OldID varchar(36) null;

----把Person的数据迁移到Emploee
----在test1运行此脚本
insert into [test2].[dbo].Emploee
([ID],[EmploeeName],[Sex],[Department],[OldID])
select newid(),Name,dbo.getSex(Sex),null,ID
from Person

----把PersonSchool的数据迁移到EmploeeSchool
----在test1运行此脚本

insert into [test2].[dbo].EmploeeSchool
(ID,EmploeeID,SchoolName,SchoolAddress)
select newid(),Emploee.ID,SchoolName,SchoolAddress
from PersonSchool ,[test2].[dbo].Emploee
where PersonSchool.PersonID=[test2].[dbo].Emploee.OldID

-----删除临时列OldID
alter table [test2].[dbo].Emploee drop column OldID;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值