日期:2014-05-17 浏览次数:20476 次
表1 [a] [b] [c] www 123 69.09 fff 998 69.08 uuu 388 69.06 表2 [e] [d] [c] [f] ttt ddd 89.12 u78 usa jio 83.21 pok 结果:表3 [a] [b] [c] [e] [d] [f] www 123 69.09 fff 998 69.08 uuu 388 69.06 89.12 ttt ddd u78 83.21 usa jio pok
declare @t table(a varchar(20),b varchar(20) ,c varchar(20)) insert into @t select 'www' , '123' , '69.09' union all select 'fff', '998', '69.08' union all select 'uuu', '388', '69.06' declare @t1 table(e varchar(20),d varchar(20),c varchar(20),f varchar(20)) insert into @t1 select 'ttt' , 'ddd ' , '89.12' , 'u78' union all select 'usa', 'jio', '83.21', 'pok' select isnull(a,'') a,isnull(b,'') b,c=ISNULL(t.c,t1.c),isnull(e,'') e,isnull(d,'') d ,isnull(f,'') f from @t t full join @t1 t1 on t.c=t1.c SELECT A,B,C,'' e,'' d,'' f FROM @t UNION ALL SELECT '','',C,E,D,F FROM @t1 /* a b c e d f -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- www 123 69.09 fff 998 69.08 uuu 388 69.06 89.12 ttt ddd u78 83.21 usa jio pok (5 行受影响) */
------解决方案--------------------
---测试数据---
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([a] varchar(3),[b] int,[c] numeric(4,2))
insert [t1]
select 'www',123,69.09 union all
select 'fff',998,69.08 union all
select 'uuu',388,69.06
if object_id('[t2]') is not null drop table [t2]
go
create table [t2]([e] varchar(3),[d] varchar(3),[c] numeric(4,2),[f] varchar(3))
insert [t2]
select 'ttt','ddd',89.12,'u78' union all
select 'usa','jio',83.21,'pok'
-->查询
declare @sql1 varchar(8000),@sql2 varchar(8000)
select @sql1=isnull(@sql1+',','')+name from syscolumns where id=object_id('t1')
select @sql1=@sql1+','''' as '+name from syscolumns where id=object_id('t2') and name not in(select name from syscolumns where id=object_id('t1'))
select @sql2=isnull(@sql2+',','')+''''' as '+name from syscolumns where id=object_id('t1') and name not in(select name from syscolumns where id=object_id('t2'))
select @sql2=@sql2+','+name from syscolumns where id=object_id('t2')
exec ('select '+@sql