方法一:自定义函数
定义Aggregate_BaseMateriel函数
GO
Create FUNCTION Aggregate_BaseMateriel(@ShipMentNo varchar(50))
RETURNS varchar(1024)
AS
BEGIN
declare @Str varchar(1024)
set @Str = ''
select @Str = @Str + ' ◆ ' + [BaseMateriel] from tb_SendShipMent_Detail
where [ShipMentNo] = @ShipMentNo
return @Str
END
GO
然后就可以写sql语句查询了,通过按ShipMentNo分组查询,得到明细中BaseMateriel的拼接结果
select detail.ShipMentNo,dbo.AggregateBaseMateriel(ShipMentNo) as materielList
from tb_SendShipMent_Detail detail
where ShipMentNo = 'XOUT20150928002'
group by detail.ShipMentNo
但是这种方法缺点是,如果多表查询,或者穿插在子查询里的话,查询速度会非常慢
--------------------------------------------------------------------------------------------------------------------------------------
方法二:使用stuff + for xml path
select [value] = stuff((select '◆'+[BaseMateriel] from tb_SendShipMent_Detail detail
where detail.ShipMentNo = 'XOUT20150928002' for xml path('')), 1, 1, '')
其中stuff的作用是:删除指定长度的字符,并在指定的起点处插入另一组字符
语法:STUFF ( character_expression , start , length ,character_expression )
列:SELECT STUFF('abcdef', 2, 3, 'ijklmn')
结果为:aijklmnef
FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现
select BaseMateriel from tb_SendShipMent_Detail 的结果为:
但是如果换成 :select BaseMateriel from tb_SendShipMent_Detail for xml path(''),结果为:
让我们来稍微改良一下,得到自己想要的拼接结果:
select '◆' + BaseMateriel from tb_SendShipMent_Detail for xml path('')
方法二无论操作简易度和查询速度都是比方法一要好