思考题:(存储函数)
表的内容: COLA COLB
4401 沥青混凝土
4401 水泥混凝土
4405 水泥混凝土
4406 沥青混凝土
4406 碎石混凝土
4412 沥青混凝土目标内容: 4401 沥青混凝土,水泥混凝土
4405 水泥混凝土
4406 沥青混凝土,碎石混凝土
4412 沥青混凝土注:查询有关存储函数的概念create table tb(COLA int, COLB varchar(10))
insert tb select 4401,'沥青混凝土'
union all select 4401,'水泥混凝土'
union all select 4405,'水泥混凝土'
union all select 4406,'沥青混凝土'
union all select 4406,'碎石混凝土'
union all select 4412,'沥青混凝土'
在SQL Server中用代码实现???
表的内容: COLA COLB
4401 沥青混凝土
4401 水泥混凝土
4405 水泥混凝土
4406 沥青混凝土
4406 碎石混凝土
4412 沥青混凝土目标内容: 4401 沥青混凝土,水泥混凝土
4405 水泥混凝土
4406 沥青混凝土,碎石混凝土
4412 沥青混凝土注:查询有关存储函数的概念create table tb(COLA int, COLB varchar(10))
insert tb select 4401,'沥青混凝土'
union all select 4401,'水泥混凝土'
union all select 4405,'水泥混凝土'
union all select 4406,'沥青混凝土'
union all select 4406,'碎石混凝土'
union all select 4412,'沥青混凝土'
在SQL Server中用代码实现???
insert tb select 4401,'沥青混凝土'
union all select 4401,'水泥混凝土'
union all select 4405,'水泥混凝土'
union all select 4406,'沥青混凝土'
union all select 4406,'碎石混凝土'
union all select 4412,'沥青混凝土'
go
create procedure unt
as
select cola,stuff((select ','+colb from tb where cola=a.cola for xml path('')),1,1,'')colb from tb a group by cola
go
exec unt
/*
cola colb
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4401 沥青混凝土,水泥混凝土
4405 水泥混凝土
4406 沥青混凝土,碎石混凝土
4412 沥青混凝土(4 行受影响)*/
go
drop table tb
drop procedure unt
a.COLA,COLB=stuff(b.COLB.value('/R[1]','nvarchar(max)'),1,1,'')
from
(select distinct COLA from tb) a
Cross apply
(select COLB=(select N','+COLB from tb where COLA=a.COLA For XML PATH(''), ROOT('R'), TYPE))b
insert tb select 4401,N'沥青混凝土'
union all select 4401,N'水泥混凝土'
union all select 4405,N'水泥混凝土'
union all select 4406,N'沥青混凝土'
union all select 4406,N'碎石混凝土'
union all select 4412,N'沥青混凝土'
GO
select
a.COLA,COLB=stuff(b.COLB.value('/R[1]',N'nvarchar(max)'),1,1,N'')
from
(select distinct COLA from tb) a
Cross apply
(select COLB=(select N','+COLB from tb where COLA=a.COLA For XML PATH(''), ROOT('R'), TYPE))b
/*
COLA COLB
4401 沥青混凝土,水泥混凝土
4405 水泥混凝土
4406 沥青混凝土,碎石混凝土
4412 沥青混凝土
*/
create function dbo.f_str(@COLA varchar(10)) returns varchar(1000)
as
begin
declare @str varchar(1000)
select @str = isnull(@str + ',' , '') + cast(COLB as varchar) from tb where COLA = @COLA
return @str
end
goselect COLA , COLB = dbo.f_str(COLA) from tb group by COLA
学习,等会儿拿下去研究研究!
thanks