日期:2014-05-17  浏览次数:20477 次

求一个函数或者存储过程,把多条记录连接成一个字段
数据:
id 编号 价格 数量 商品说明
1  101  1    2    说明1
2  101  11   3    说明2
3  102  2    4    说明3
4  102  22   5    说明4

执行函数后返回:
编号   内容
101   说明1,价格1,数量2;说明2,价格11,数量3
102   说明3,价格2,数量4;说明4,价格22,数量5

------解决方案--------------------
适合2005及以上版本:
create table tb(id int, 编号 int, 价格 int, 数量 int,商品说明 varchar(100))

insert into tb
select 1  ,101,  1 ,   2    ,'说明1' union all
select 2  ,101,  11,   3    ,'说明2' union all
select 3  ,102,  2 ,   4    ,'说明3' union all
select 4  ,102,  22,   5    ,'说明4'
go

select distinct
       编号,
       stuff((select ','+ 商品说明 +
                     ',价格'+ CAST(价格 as varchar) +
                     ',数量'+ CAST(数量 as varchar) +';'
              from tb t2
              where t1.编号= t2.编号
              for XML path('')
             ),1,1,'') as 内容
from tb t1
/*
编号 内容
101 说明1,价格1,数量2;,说明2,价格11,数量3;
102 说明3,价格2,数量4;,说明4,价格22,数量5;
*/

------解决方案--------------------

--1)創建數據:
CREATE TABLE test_data (id int,编号 int,价格 int,数量 int,商品说明 VARCHAR(50))

INSERT test_data
SELECT 1,  101,  1,    2,'说明1' UNION ALL
SELECT 2,  101,  11,   3,'说明2' UNION ALL
SELECT 3,  102,  2,    4,'说明3' UNION ALL
SELECT 4,  102,  22,   5,'说明4'

--2)創建函數:
CREATE &nbs