提一个常见的问题

xiaoyi1981 2004-11-22 12:01:28
表A(id,Pid)
表A有如下记录
id Pid
1 01
1 02
2 03
2 02
2 05
怎么样实现
id Pid
1 01,02
2 02,03,05
...全文
111 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Andy__Huang 2004-11-22
  • 打赏
  • 举报
回复
參考﹕

--建表
create table tb (A varchar(10),B varchar(1000))
Insert into tb
select '111','AA0000,AA0001,AA0002,'
union all select '111','BB0000,BB0001,BB0002,'
union all select '222','AA0120,AA0102,AA1453,'
union all select '222','BB1212,BB3423,BB2123,'

select * from tb

--函數
create function dbo.fn_b(@a varchar(10))
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
select @s=@s+[B] from tb where A=@a
return (@s)
end

--刪除
drop table tb
drop function dbo.fn_b

--結果
select A,B=dbo.fn_b(A) from tb group by A
A B
-------------------------------------------
111 AA0000,AA0001,AA0002,BB0000,BB0001,BB0002,
222 AA0120,AA0102,AA1453,BB1212,BB3423,BB2123,
lipkissnow 2004-11-22
  • 打赏
  • 举报
回复
我曾想用游標來寫.但看到上面大家給出的是用函數的.我就想到一個問題是.用游標寫和用函數哪一個消耗系統資源最少.
lipkissnow 2004-11-22
  • 打赏
  • 举报
回复
學習
davorsuker39 2004-11-22
  • 打赏
  • 举报
回复
create table ta (id int, value varchar(20))
Insert into ta
select '1','aaa'
union all select '2','bbb'
union all select '3','ccc'

create table tb (id int, value varchar(20))
Insert into tb
select '1','aaa,bbb,'
union all select '2','bbb,ccc,'
union all select '3','aaa,bbb,ccc,'

select * from ta
select * from tb

--函數
create function dbo.fn_m(@vchstring varchar(1000))
returns varchar(1000)
as
begin
declare @intstart int,@intlocation int
declare @s varchar(1000),@vchsubstring varchar(100)

select @intstart =1,@s=''
select @intlocation = charindex(',',@vchstring,@intstart)
while (@intlocation <>0 )
begin
select @vchsubstring=substring(@vchstring,@intstart,@intlocation-@intstart)
select @s=@s+cast([id] as varchar)+',' from ta where value=@vchsubstring
select @intstart = @intlocation +1
select @intlocation = charindex(',',@vchstring,@intstart)
end
return(@s)
end

--刪除
drop table ta
drop table tb
drop function dbo.fn_m

select id, value=dbo.fn_m(value) from tb
--結果
id value
------------------
1 1,2,
2 2,3,
3 1,2,3,
bqb 2004-11-22
  • 打赏
  • 举报
回复
create table test(id int,Pid varchar(20))
insert test(id,Pid)
select 1,'01'
union all
select 1,'02'
union all
select 2,'02'
union all
select 2,'03'
union all
select 2,'02'
union all
select 2,'05'

select * from test


id Pid
----------------
1 01
1 02
2 02
2 03
2 02
2 05



create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+','+cast(pid as varchar) from test where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go

select distinct id,dbo.fmerg(id) Pid from test

id Pid
--------------
1 01,02
2 02,03,02,05


--刪除
drop table test
drop function dbo.fmerg

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧