SQLSqlserver中如何将一列数据拼接成一个字符串


创建表值函数:

[sql]  view plain  copy
  1. create function [dbo].[GetAssessmentCity](    
  2. @ryear varchar(4), --年份    
  3. @rmonth varchar(2)  --月份    
  4. returns @GetCity TABLE(id varchar(20),city varchar(20))    
  5. as     
  6. begin    
  7.     declare @result varchar(1200) --返回结果    
  8.     insert into @GetCity     
  9.     select 1,a.AssessmentCity from T_COD_SectionInfo a     
  10.     right join MonthTargetData b on a.section_id=b.section_id     
  11.     where (report_year = @ryear    
  12.            and report_month = @rmonth)    
  13.            and (value61 = 1    
  14.             or value62 = 1)    
  15.    return    
  16. end    

SQL语句:

[sql]  view plain  copy
  1. SELECT b.id,LEFT(cityList,LEN(cityList)-1) city FROM (    
  2.     SELECT  id, (SELECT city+'、' FROM dbo.GetAssessmentCity('2012','01'WHERE id=a.id FOR XML PATH(''))     
  3.     AS cityList FROM dbo.GetAssessmentCity('2012','01') a group by id) b   

简单示例:

[sql]  view plain  copy
  1. declare @T Table(Id numeric(18), Code varchar(10))    
  2. insert into @T(id,code)    
  3. select 1, 'zhang'    
  4. union all    
  5. select 1, 'yan'    
  6. union all    
  7. select 2, 'zdw'    
  8. union all    
  9. select 2, 'ydj';    
  10.     
  11. SELECT B.id,LEFT(UserList,LEN(UserList)-1) code FROM (    
  12. SELECT id,(SELECT code+',' FROM @T WHERE id=A.id FOR XML PATH('')) AS UserList FROM @T A GROUP BY id    
  13. ) B    

方法二:

[sql]  view plain  copy
  1. declare @output varchar(8000)    
  2. select @output = coalesce(@output + ',' , '') + name from (SELECT DISTINCT(name)     
  3.         FROM a where R_control='国控' and R_type='重金属河流')AS T    
  4. print @output    
  5. go    

方法三:

[sql]  view plain  copy
  1. DECLARE @STR VARCHAR(8000)    
  2. SELECT @STR=ISNULL(@STR+',','')+name FROM (SELECT DISTINCT(name)     
  3.     FROM a where R_control='国控' and R_type='重金属河流')AS T    
  4. SELECT @STR    
  5. go    

转自:http://blog.csdn .NET /mh942408056/article/details/7417857






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值