String.Join in SQL

前端 未结 4 606
独厮守ぢ
独厮守ぢ 2021-01-18 19:17

i want to select from a Table called RMA(simplified):

 idRMA| RMA_Number
 -----------------------
 1      RMA0006701
 2      RMA0006730
 3               


        
4条回答
  •  深忆病人
    2021-01-18 20:04

    Use the classic XML PATH-trick for this:

    declare @RMA  as table(idRMA int, RMA_Number nvarchar(20))
    
    declare @trelRMA_SymptomCode as table (fiSymptomCode int, fiRMA int)
    
    declare @tdefSymptomCode as table (idSymptomCode int, SymptomCodeNumber nvarchar(4), SymptomCodeName nvarchar(20))
    
    insert into @RMA values
    (1,      'RMA0006701'),
    (2,      'RMA0006730'),
    (3,      'RMA0006736'),
    (4,      'RMA0006739'),
    (5,      'RMA0006742')
    
    insert into @trelRMA_SymptomCode values
    (1,              1),
    (1,              2),
    (2,              2),
    (5,              3),
    (7,              3),
    (8,              3),
    (2,              5),
    (3,              5),
    (4,              5),
    (5,              5)
    
    insert into @tdefSymptomCode values
    (1,                '0000',                   'Audio problem'),
    (2,                '0100',                   'SIM problem'),
    (3,                '0200',                   'Appearance problem'),
    (4,                '0300',                   'Network problem'),
    (5,                '0500',                   'On/Off problem')
    
    select RMA_Number,
     STUFF(
        (
        SELECT
          ':' + SymptomCodeNumber
        FROM @tdefSymptomCode def 
        join @trelRMA_SymptomCode rel on def.idSymptomCode = rel.fiSymptomCode
        where rel.fiRMA=rma.idRMA
        FOR XML PATH('')
        ), 1, 1, '')
    from @rma rma
    

    results in

    RMA0006701  0000
    RMA0006730  0000:0100
    RMA0006736  0500
    RMA0006739  NULL
    RMA0006742  0100:0200:0300:0500
    

提交回复
热议问题