Reputation: 6512
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'
Upvotes: 3
Views: 1538
Reputation: 44326
declare @groups nvarchar(1000) ='group1,group10,group8'
set @groups = 'rmc.' + replace(@groups, ',', ',rmc.')
select @groups
Result:
rmc.group1,rmc.group10,rmc.group8
Upvotes: 4
Reputation: 121932
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
Upvotes: 2