今天碰到一个需求,将多行数据id值,变成一列,并更新到制定列中,在网上找了也没好的方法,最后自己写了一个实现,语句如下:
create FUNCTION stTable
(
@id varchar(32)
)
RETURNS @st TABLE (id varchar(8000))
begin
declare @sql as varchar(8000);
set @sql=''
select @sql=@sql+','+objid2+''
from (select distinct objid2 from dbo.refobjlink where objid1=@id and
linktype='project3') b
set @sql=substring(@sql,2,len(@sql))
insert into @st values(@sql)
return
end
GO
update project set numbers=t.id
from project
CROSS APPLY stTable(project.id) t
GO
(
@id varchar(32)
)
RETURNS @st TABLE (id varchar(8000))
begin
declare @sql as varchar(8000);
set @sql=''
select @sql=@sql+','+objid2+''
from (select distinct objid2 from dbo.refobjlink where objid1=@id and
linktype='project3') b
set @sql=substring(@sql,2,len(@sql))
insert into @st values(@sql)
return
end
GO
update project set numbers=t.id
from project
CROSS APPLY stTable(project.id) t
GO
结果是:
原有多行的数据:
1
2
3
4
5
转化为一列的数据:
1,2,3,4,5
1
2
3
4
5
转化为一列的数据:
1,2,3,4,5