当前位置: 代码迷 >> Sql Server >> 自定义函数合并动态列请问
  详细解决方案

自定义函数合并动态列请问

热度:84   发布时间:2016-04-24 09:20:22.0
自定义函数合并动态列请教
有一个表 test,数据如下,
id   Name
mx  aaa
mx  bbb
zm  ccc
dy   ggg
dy   eee

要写一个函数,输入 mx,得到 aaa,bbb,输入 zm,得到 ccc,输入dy,输出ggg,eee
请问怎么写这个函数?


------解决思路----------------------
with a(id,name) as
(
 select 'mx','aaa' union all
 select 'mx','bbb' union all
 select 'zm','ccc' union all
 select 'dy','ggg' union all
 select 'dy','eee'
)

select distinct id,stuff((select ','+name from a as b 

where a.id=b.id for xml path('')),1,1,'') as tx
 
 from a where a.id='mx'
 
 /**
 id  tx
---------------
 mx aaa,bbb
---------------
 **/

------解决思路----------------------

create table test
(id varchar(10),name varchar(10))

insert into test
 select 'mx','aaa' union all
 select 'mx','bbb' union all
 select 'zm','ccc' union all
 select 'dy','ggg' union all
 select 'dy','eee'
 

-- 创建函数
create function dbo.fn_test
(@id varchar(10)) returns varchar(50)
as
begin
 declare @names varchar(50)
 
 select @names=isnull(@names+',','')+name
  from test
  where id=@id

 return @names
end


-- 输入 mx
select dbo.fn_test('mx') 'names'
/*
names
--------------------------------------------------
aaa,bbb

(1 行受影响)
*/


-- 输入 zm
select dbo.fn_test('zm') 'names'
/*
names
--------------------------------------------------
ccc

(1 行受影响)
*/


-- 输入dy
select dbo.fn_test('dy') 'names'
/*
names
--------------------------------------------------
ggg,eee

(1 行受影响)
*/
  相关解决方案