简体   繁体   中英

how to split and concatenate in sql server?

I am passing in a string into a stored procedure to be used in a select statement using dynamic sql:

@groups as nvarchar(1000) = 'group1,group10,group8'

I might just pass in string of numbers, eg, '1,2,3,4'

I want to split these values and then concatenate them so that they end up in the following manner :

'rmc.group1,rmc.group10,rmc.group8'
declare @groups nvarchar(1000) ='group1,group10,group8'

set @groups = 'rmc.' + replace(@groups, ',', ',rmc.')
select @groups

Result:

rmc.group1,rmc.group10,rmc.group8

Sql小提琴演示

Select Replace('group1,group10,group8','group','rmc.group')

Try this one -

DECLARE @groups nvarchar(1000) = 'group1,group10,group8'

SELECT STUFF((
    SELECT ',rmc.' + t
    FROM (
          SELECT t = t.c.value('.', 'VARCHAR(50)')
          FROM (
               SELECT ID = CAST ('<t>' + REPLACE(@groups, ',', '</t><t>') + '</t>' AS XML)
          ) r 
          CROSS APPLY ID.nodes ('/t') t(c)
    ) t
    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1,1, '')

Output -

------------------------------------
rmc.group1,rmc.group10,rmc.group8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM