求SQL語句
Declare @Ta Table (ModuleID int,FieldName Char(5))
insert @Ta
Select 100,'Qty3' Union
Select 100,'Qty4' Union
Select 101,'Qty2' Union
Select 101,'Qty3' Union
Select 101,'Qty4' Union
Select 101,'Qty5'
Declare @Tb Table (ModuleID int,Qty1 int,Qty2 int,Qty3 int,Qty4 int,Qty5 int)
Insert @Tb
Select 100,10,15,1,30,2 Union
Select 101,11,13,31,8,25
1、當選擇的ModuleID為100時,@Ta表的FieldName值為Qty3,Qty4;那麼我只需要@Tb表的字段Qty3,Qty4的值,即1,30
2、當選擇的ModuleID為101時,@Ta表的FieldName值為Qty2,Qty3,Qty4,Qty5;那麼我只需要@Tb表的字段Qty2,Qty3,Qty4,Qty5的值,即15,1,30,2
以上SQL語句如何實現,虛心求教。謝!
------解决方案--------------------能不能用简体字啊
------解决方案--------------------如果不用临时表的话,@ta为ta表,@tb为tb表
declare @sql varchar(max)
declare @a varchar(max)
declare @b int
set @b=101
select distinct ModuleID,
a=stuff((select ','+FieldName from ta where a.ModuleID=ModuleID for xml path('') ),1,1,'')
into #t from ta a
where ModuleID=@b
select @a=a from #t
exec('select '+@a+' from tb where moduleid='+@b)