我想从一个称为RMA
的表中进行选择(简化):
idRMA| RMA_Number
-----------------------
1 RMA0006701
2 RMA0006730
3 RMA0006736
4 RMA0006739
5 RMA0006742
RMA
和tdefSymptomCode
之间有一个连接表,称为trelRMA_SymptomCode
: fiSymptomCode| fiRMA
-----------------------
1 1
1 2
2 2
5 3
7 3
8 3
2 5
3 5
4 5
5 5
为了完整起见,这是
tdefSymptomCode
:idSymptomCode SymptomCodeNumber SymptomCodeName
1 0000 Audio problem
2 0100 SIM problem
3 0200 Appearance problem
4 0300 Network problem
5 0500 On/Off problem
问:
每个RMA可以具有0-5个症状代码。如何在标量值函数中将带有':'之类的分隔符的SymptomCodeNumber连接在一起,这样我只能得到一个varchar值。
像这样的东西(其中
getRmaSymptomCodes
是SVF):SELECT idRMA, RMA_Number, dbo.getRmaSymptomCodes(idRMA,':') AS Symptoms FROM RMA
这可能是3种不同RMA的症状(均具有一种症状):
RMA_Number SymptomCodeNumber
RMA0004823 0100
RMA0004823 0200
RMA0000083 0300
RMA0000084 0300
RMA0000084 0400
应将其串联为:
RMA0004823 0100:0200
RMA0000083 0300
RMA0000084 0300:0400
先感谢您
更新:多亏我创建了这个工作功能
CREATE FUNCTION [dbo].[getRmaSymptomCodes]
(
@idRMA int,
@delimiter varchar(5)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Codes VARCHAR(8000)
SELECT @Codes = COALESCE(@Codes + @delimiter, '') + tdefSymptomCode.SymptomCodeNumber
FROM RMA INNER JOIN
trelRMA_SymptomCode ON RMA.IdRMA = trelRMA_SymptomCode.fiRMA INNER JOIN
tdefSymptomCode ON trelRMA_SymptomCode.fiSymptomCode = tdefSymptomCode.idSymptomCode
where idRMA=@idRMA
order by SymptomCodeNumber
return @Codes
END
最佳答案
这样可以吗?
DECLARE @Codes VARCHAR(8000)
SELECT @Codes = COALESCE(@Codes + ', ': '') + tdefSymptomCode.SymptomCodeNumber
FROM RMA INNER JOIN
trelRMA_SymptomCode ON RMA.IdRMA = trelRMA_SymptomCode.fiRMA INNER JOIN
tdefSymptomCode ON trelRMA_SymptomCode.fiSymptomCode = tdefSymptomCode.idSymptomCode
where idRMA=2
order by SymptomCodeNumber
return @Codes