2014-02-19 79 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);