declare @sql1 varchar(7000),@sql varchar(7000)
set @sql1 = ' select '
select @sql1 = @sql1+'sum(case t_item.fname when '''+fname+''' then icstockbillentry.fentryselfb0161 else 0 end) as '''+fname+''','
from (select distinct t_item.fname from icstockbillentry left join t_item on fdcstockid=t_item.fitemid where t_item.ffullname like '%AUP%' ) as a
select @sql1 = left(@sql1,len(@sql1)-1) + 'from icstockbill left join icstockbillentry on icstockbill.finterid=icstockbillentry.finterid left join t_item on t_item.fitemid=icstockbillentry.fdcstockid
where fstatus=1 and fbillno like ''%pos%'' and t_item.ffullname like ''%aup%'' and icstockbill.fdate between ''20090101'' and ''20090131'''
execute (@sql1)