一个表,两个字段,要查询成 username biz1,biz2,biz3这样的形式
例如:
username biz
u1 b1
u2 b2
u3 b3
u2 b4
查询出的如果如下:
u1 b1
u2 b2,b4
u3 b3
找个好方法
create table tb
(
username char(10),
biz nvarchar(10)
)
insert into tb(username ,biz) values('u1','b1')
insert into tb(username ,biz) values('u2','b2')
insert into tb(username ,biz) values('u3','b3')
insert into tb(username ,biz) values('u2','b4')
go
--创建一个合并的函数
create function f_hb(@a varchar(10))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + biz from tb where username=@a
set @str = right(@str , len(@str) - 1)
return(@str)
End
go
select distinct username ,dbo.f_hb(username) as biz from tb
drop function f_hb
drop table tb
结果 :
username biz
---------- ----------
u1 b1
u2 b2,b4
u3 b3
(所影响的行数为 3 行)
楼主正解,用一简单的函数就可以实现了
create table tb
(
username char(10),
biz nvarchar(10)
)
insert into tb(username ,biz) values('u1','b1')
insert into tb(username ,biz) values('u2','b2')
insert into tb(username ,biz) values('u3','b3')
insert into tb(username ,biz) values('u2','b4')
create function test_f (@username varchar(10))
returns varchar(100)
as
begin
declare @s varchar(100)
set @s=''
select @s=@s+','+biz from tb where username=@username
return(stuff(@s,1,1,''))
end
select distinct username,biz=dbo.test_f(username)from tb
username biz
---------- --------------
u1 b1
u2 b2,b4
u3 b3
(所影响的行数为 3 行)