字符串叠加

liberationxin 2008-06-13 11:59:53
表Ab ,字段为 Id , GuiGe 内容
001 300*300
001 300*400
002 200*300
003 100*100
001 400*400
002 400*400
我想得到 结果如下
ID GuiGeStr
001 300*300/300*400/400*400
002 200*300/400*400
003 100*100

以下是我部分程序,字符串没有叠加,请赐教
declare @IdOld varchar(15),@GuiGeStrs varchar(100)
select @IdOld='',@GuiGeStr =''
create table #b(Id int,GuiGe varchar(15),GuiGeStr varchar(100))
insert into #a (Id,GuiGe ,GuiGeStr)
select Id,GuiGe ,GuiGeStr,'' from Ab order by Id
update #a set GuiGeStr =@GuiGeStrs,@GuiGeStrs=case when Id=@IdOld then @GuiGeStrs+'/'+GuiGe else GuiGe end ,@IdOld=Id
怎么没有修改呢?
...全文
134 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinqi025 2008-06-13
  • 打赏
  • 举报
回复
if object_id('tb') is not null
begin
drop table tb
end
if object_id('f_g') is not null
begin
drop function f_g
end
go

create table tb(id varchar(64),GuiGe varchar(64))
insert into tb
select '001','300*300'
union all
select '001','300*400'
union all
select '002','200*300'
union all
select '003','100*100'
union all
select '001','400*400'
union all
select '002','400*400'
go

--code
create function f_g(@id varchar(64))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+'/'+GuiGe from tb
where id=@id
return stuff(@str,1,1,'')
end
go

select id,dbo.f_g(id) as 结果 from tb
group by id
yinqi025 2008-06-13
  • 打赏
  • 举报
回复
嗯...也可以写自定义聚合函数...
-狙击手- 2008-06-13
  • 打赏
  • 举报
回复

-- Test Data: ta
If object_id('ta') is not null
Drop table ta
Go
Create table ta(Id int,GuiGe varchar(7))
Go
Insert into ta
select 001,'300*300' union all
select 001,'300*400' union all
select 002,'200*300' union all
select 003,'100*100' union all
select 001,'400*400' union all
select 002,'400*400'
Go
create table #a(Id int,GuiGe varchar(15),GuiGeStr varchar(100))
go
--Start
declare @IdOld varchar(15),@GuiGeStrs varchar(100)
select @IdOld='',@GuiGeStrs =''

insert into #a (Id,GuiGe ,GuiGeStr)
select Id,GuiGe ,'' from ta order by Id
update #a
set GuiGeStr =@GuiGeStrs,
@GuiGeStrs=case when Id=@IdOld then @GuiGeStrs+'/'+GuiGe else GuiGe end ,@IdOld=Id

select * from #a
drop table #a
--Result:
/*
Id GuiGe GuiGeStr
----------- --------------- ----------------------------------------------------------------------------------------------------
1 300*300 300*300
1 300*400 300*300/300*400
1 400*400 300*300/300*400/400*400
2 400*400 400*400
2 200*300 400*400/200*300
3 100*100 100*100

(所影响的行数为 6 行)

*/
--End

lff642 2008-06-13
  • 打赏
  • 举报
回复


insert into #a (Id,GuiGe ,GuiGeStr)
select Id,GuiGe ,GuiGeStr,'' from Ab order by Id

这里插入字段都有问题.

中国风 2008-06-13
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20080612/22/c850499f-bce3-4877-82d5-af2357857872.html
以上整理的方法
liberationxin 2008-06-13
  • 打赏
  • 举报
回复
我写的哪个地方出问题了?

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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