将表中一个字段内容放在一起显示

将表中一个字段内容放在一起显示

 

[sql] 
--声明表变量  
declare @t table (strid int,strname nvarchar(50))  
  
--插入测试数据  
insert into @t  
select 1,'a1' union all  
select 1,'a2' union all  
select 1,'a3' union all  
select 2,'b1' union all  
select 2,'b2' union all  
select 2,'b3' union all  
select 3,'c1' union all  
select 3,'c2' union all  
select 3,'c3'  
  
--计算结果  
select t.strid,  
       [contents] = stuff(  
           (  
               select '/' + convert(nvarchar(50),r.strname)  
               from   @t r  
               where  r.strid=t.strid for xml path('')  
           ),  
           1,  
           1,  
           ''  
       )  
from   @t t  
group by  
       t.strid  
for xml path('') sql2005以后的版本支持生成一种xml文档的方式。

path(‘’):控制节点的名称

 

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐