2014-02-19 75 views
0

你好,我只是想知道的东西.. 说我有这个下面的查询..SQL的东西,凝聚

DECLARE @earninglist varchar(1000) 
     Set @earninglist=STUFF((SELECT DISTINCT '],[' 
      +LTRIM([Description]) FROM 
      PR_Earnings 
      ORDER BY '],[' + LTRIM([Description]) 
         FOR XML PATH('') 
         ), 1, 2, '')+']' 

Declare @sql varchar(max) 
set @sql='Select '[email protected]+' from earnings;' 
exec(@sql); 

说,收入列表包含此字段:“可口可乐”,“激励” 哪有我宣布@earninglist,这样我可以得到这个下面的查询:使用的东西..请帮助

set @sql='Select Coalesce([Cola],0)Cola,Coalesce([Incentives],0)Incentives from earnings' 

..

嗯..如果您发现该@earninglist第一套@sql ..它会变成这样:'Select [Cola],[Incentives] from earnings'我想要做的是使@earninglist的结果集是这样的:'Select Coalesce([Cola],0)Cola,Coalesce([Incentives],0)Incentives from earnings' ..是否有可能?

回答

1

尝试为:

DECLARE @earninglist varchar(1000) 
     Set @earninglist=STUFF((SELECT DISTINCT '],Coalesce([' +LTRIM([Description])+'],0)['+LTRIM([Description]) FROM 
      PR_Earnings 
      ORDER BY '],Coalesce([' +LTRIM([Description])+'],0)['+LTRIM([Description]) 
         FOR XML PATH('') 
         ), 1, 2, '')+']' 

Declare @sql varchar(max) 
set @sql='Select '[email protected]+' from earnings;' 
exec (@sql);