读书人

怎么用另一个表的查询结果作为另外一个

发布时间: 2012-02-22 19:36:55 作者: rapoo

如何用另一个表的查询结果作为另外一个表的字段
比如我有表一
T1
字段为:f1,f2,f3
表2 T2
字段为id, value
表1有内容为
f1 f2 f3
--------
a b c
表2有内容为
id value
----------
1 10
2 20
现在要组合新表为
f1 f2 f3 10 20
----------------------
a b c (底下不要求有值)

如何实现,谢谢



[解决办法]
如果表1和表2的字段是个数固定可以用动态的方法修改表的字段名称来到达你的目的。
[解决办法]
create table t1(f1 int,f2 int,f3 int)
insert t1 select 1,2,3

create table t2(id int,value int)
insert t2 select 1,10
union select 2,20

declare @value1 int,@value2 int
select @value1=value from t2 where id=1
select @value2=value from t2 where id=2

exec( 'select *,null [ '+@value1+ '],null [ '+@value2+ '] from t1 ')

drop table t1,t2

读书人网 >SQL Server

热点推荐