表1 表2
编号 属性1 编号 属性2
1 11 1 111
1 12 1 112
1 13 2 221
2 21 2 222
3 31 4 441
将以上两个表合并成表3
编号 属性1 属性2
1 11 111
1 12 112
1 13 null
2 21 221
2 null 222
3 31 null
4 null 441
------------------------------------------部分代码declare @tb1 table(编号 int,属性1 int)
insert @tb1 select 1 , 11
insert @tb1 select 1 , 12
insert @tb1 select 1 , 13
insert @tb1 select 2 , 21
insert @tb1 select 3 , 31
declare @tb2 table(编号 int,属性1 int)
insert @tb2 select 1 , 111
insert @tb2 select 1 , 112
insert @tb2 select 2 , 221
insert @tb2 select 2 , 222
insert @tb2 select 4 , 441
select * from @tb1
select * from @tb2
编号 属性1 编号 属性2
1 11 1 111
1 12 1 112
1 13 2 221
2 21 2 222
3 31 4 441
将以上两个表合并成表3
编号 属性1 属性2
1 11 111
1 12 112
1 13 null
2 21 221
2 null 222
3 31 null
4 null 441
------------------------------------------部分代码declare @tb1 table(编号 int,属性1 int)
insert @tb1 select 1 , 11
insert @tb1 select 1 , 12
insert @tb1 select 1 , 13
insert @tb1 select 2 , 21
insert @tb1 select 3 , 31
declare @tb2 table(编号 int,属性1 int)
insert @tb2 select 1 , 111
insert @tb2 select 1 , 112
insert @tb2 select 2 , 221
insert @tb2 select 2 , 222
insert @tb2 select 4 , 441
select * from @tb1
select * from @tb2
crate tabke a
(
id int not null,
s1 varchar(10) null,
s2 varchar(10) null
)
insert into a (id,s1,s2) select A.编号,A.属性1,B.属性1 from @tb1 A left join @tb2 B on A. 编号=B.编号 insert into a (id,s1,s2) select B.编号,A.属性1,B.属性1 from @tb1 A right join @tb2 B on A. 编号=B.编号 where A.属性1 is null
--select * from #a
select 编号,cast(substring(cast(属性1 as varchar),2,2) as int) as 属性1,属性1 as 属性2 into #b from @tb2
--select * from #b
select #a.编号,#a.属性1,#a.属性2 from #a left join #b on #a.编号=#b.编号 and #a.属性1=#b.属性1
union
select #b.编号,#b.属性1,#b.属性2 from #b left join #a on #a.编号=#b.编号 and #a.属性1=#b.属性1