34,589
社区成员
发帖
与我相关
我的任务
分享
declare @sql varchar(2000)
select @sql=isnull(@sql+',','select ')+ colname from tb1 where ckflag=1
exec(@sql+' from tb2' )
--动态语句
declare @sql varchar(max)
select @sql=isnull(@sql+',','select ')+
(select distinct colname
from tb1
where ckflag=1)
exec(@sql+' from tb2' )
if object_id('tb1') is not null drop table tb1
go
create table tb1 (id int,colname varchar(5),ckflag int)
insert tb1
select 1 ,'col1', 1 union all
select 2 ,'col2', 0 union all
select 3 ,'col3', 1 union all
select 4 ,'col4', 1 union all
select 5 ,'col5', 0
go
if object_id('tb2') is not null drop table tb2
go
create table tb2 (col1 varchar(3), col2 varchar(4), col3 int, col4 numeric(3,2) ,col5 numeric(3,2))
insert tb2
select '001', '白色', 10, 0.07, 0.7 union all
select '002', '红色', 8, 0.18 ,1.44
go
declare @sql varchar(8000)
select @sql=isnull(@sql+',','select ')+ colname from tb1 where ckflag=1
exec(@sql+' from tb2' )
/*
col1 col3 col4
---- ----------- -----
001 10 .07
002 8 .18
(所影响的行数为 2 行)
*/