我现在有多个库结构相同的数据库,需要把数据合并到一个库结构相同的总库中,但是数据库中各表之间的关系要求能自动对应。
例如;A库中的两个表b,c
b表中有 id 管理id 姓名
1 2 张三
c表中有 id 管理id
1 2
合并到总库中后,同样有c表但是合并过来的数据可能是 管理id不是2了,如何做到合并B表中的数据时,管理id 能自动对应c表中的新数据。
例如;A库中的两个表b,c
b表中有 id 管理id 姓名
1 2 张三
c表中有 id 管理id
1 2
合并到总库中后,同样有c表但是合并过来的数据可能是 管理id不是2了,如何做到合并B表中的数据时,管理id 能自动对应c表中的新数据。
我都是用id做为连接字段,但是合并的时候id就发生改变时,与之有关系的表的相关字段也能改变。
on c
for update
as
if (select count(1) from inserted)>0
begin
update b set id=t.id,管理id=t.管理id
from inserted t
endgo
on c
for update
as
if (select count(1) from inserted)>0
begin
update b set id=t.id,管理id=t.管理id
from inserted t1,deleted t2
where id=t2.id
endgo
例如,我数据库中原来已经有了5条记录,id自然是1到5,如果合并数据,新增的记录应该自动为6,然后更改与其有对应关系的表中的相关字段。我感觉应该编程序实现。但是数据量很大,想问问大家有什么好办法没有???
id,管理id,名称,地址
管理:
id,名称
车辆档案:
id,业户id,车牌号
先列举三个吧
还有很多。这三个表之间的表间关系就是 管理表中的id 对应业户档案中的业户id,业户档案表中的id对应车辆档案中的业户id.
a库
b表中有 id 管理id 姓名
1 2 张三
c表中有 id 管理id
1 2b库
b表中有 id 管理id 姓名
1 2 李四
c表中有 id 管理id
1 2
合并到c库b表中有 id 管理id 姓名
1 2 张三
2 3 李四
c表中有 id 管理id
1 2
2 3
--a库
--创建测试环境
create table #档案a(id int,管理id int)
create table #管理a(id int)--插入测试数据
insert #档案a(id,管理id)
select '1','1' union all
select '2','2'insert #管理a(id)
select '1' union all
select '2'
--b库
--创建测试环境
create table #档案b(id int,管理id int)
create table #管理b(id int)--插入测试数据
insert #档案b(id,管理id)
select '1','1' union all
select '3','3'insert #管理b(id)
select '1' union all
select '3'declare @max_管理a_id int,@max_档案a_id int
select @max_管理a_id = max(id) from #管理a
select @max_档案a_id = max(id) from #档案a
--c库create table #档案c(id int,管理id int)
create table #管理c(id int)insert #档案c
select * from #档案a
union all
select id+@max_档案a_id,管理id + @max_管理a_id from #档案binsert #管理c
select * from #管理a
union all
select id+@max_管理a_id from #管理bselect * from #档案c
/*--测试结果
id 管理id
----------- -----------
1 1
2 2
3 3
5 5
*/
select * from #管理c
/*--测试结果
id
-----------
1
2
3
5
*/
--删除测试环境
drop table #档案a,#管理a,#档案b,#管理b,#档案c,#管理c
id,管理id,名称,地址
管理:
id,名称
车辆档案:
id,业户id,车牌号
先列举三个吧
还有很多。这三个表之间的表间关系就是 管理表中的id 对应业户档案中的业户id,业户档案表中的id对应车辆档案中的业户id.
--这是最容易的写法,合并后可能会出现id不连续
--a库
--创建测试环境
create table #档案a(id int,管理id int)
create table #管理a(id int)--插入测试数据
insert #档案a(id,管理id)
select '1','1' union all
select '2','2'insert #管理a(id)
select '1' union all
select '2'
--b库
--创建测试环境
create table #档案b(id int,管理id int)
create table #管理b(id int)--插入测试数据
insert #档案b(id,管理id)
select '1','1' union all
select '3','3'insert #管理b(id)
select '1' union all
select '3'declare @max_管理a_id int,@max_档案a_id int
select @max_管理a_id = max(id) from #管理a
select @max_档案a_id = max(id) from #档案a
--c库create table #档案c(id int,管理id int)
create table #管理c(id int)insert #档案c
select * from #档案a
union all
select id+@max_档案a_id,管理id + @max_管理a_id from #档案binsert #管理c
select * from #管理a
union all
select id+@max_管理a_id from #管理bselect * from #档案c
/*--测试结果
id 管理id
----------- -----------
1 1
2 2
3 3
5 5
*/
select * from #管理c
/*--测试结果
id
-----------
1
2
3
5
*/
--删除测试环境
drop table #档案a,#管理a,#档案b,#管理b,#档案c,#管理c