两表JOIN不取指定的表字段
我有两表A和B A.A=B.B,A,B表中除了A.A和 B.B是能确定的,A.1...A.3 或B.1...B.3是不确定的,有可以是A(B).1---A(B).20,也有可以是A(B).10---A(B).30,现在我想取两表JOIN的结果集,除了B.B或A.A不取,其余的全取,请问要怎样写SQL?
------------A表------------- | ------------B表------------
a.a a.1 a.2 a.3 ...| b.b b.1 b.2 b.3 ...
不 0 1 3 ...| 不 0 0 0 ...
服 3 1 0 ...| 服 1 0 1 ...
家 4 0 2 ...| 家 1 0 0 ...
食 3 2 6 ...| 食 1 1 2 ...
行 4 0 2 ...| 行 1 0 1 ...
租 0 2 0 ...| 租 0 0 1 ...
合 14 6 13 ...| 合 4 1 5 ...
谢谢赐教!
------解决方案--------------------declare @a varchar(5000)
declare @b varchar(5000)
select @a=coalesce(@a+ ', ', ' ')+ '[ '+name+ '] ' from syscolumns where id=object_id( 'A ') and name <> 'a ' order by colid
select @a=@a+ ', '+ '[ '+name+ '] ' from syscolumns where id=object_id( 'B ') and name <> 'b ' order by colid
set @b= 'select '+@a+ ' from A Inner Join B On A.a=B.b '
exec(@b)
------解决方案--------------------select @icount1 = count(*) from syscolumns where id = object_id( 'A ')
select @icount2 = count(*) from syscolumns where id = object_id( 'B ')
decalre @sql1 varchar(8000),
@sql2 varchar(8000)
decalre @i int
set @i = 1
select @sql1 = 'select ',@sql2 = ' '
while @i < @icount1
begin
set @sql1 += 'a. '+@i+ ', '
set @i+=1
end
set @i = 1
while @i < @icount2
begin
set @sql1 += 'b. '+@i+ ', '
set @i += 1
end
set @sql2 = right(@sql,1,len(@sql1)-1)
set @sql2 += 'from a,b where a.a = b.b '
exec(@sql2)
------解决方案--------------------1.你把临时表作成永久表不是一样吗?
2.非要用临时表,那就在tempdb..sysobjects 和tempdb..syscolumns里查