Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split varchar and looping it then merge to varchar with ' , ' separator

i have data varchar like this
'201,203'

i want split and want get data from relation other table like this

Code Name
201 room A
203 room B

i want the result is varchar and split result with separators coma ‘, ‘ like this
room A, room B

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may first construct a function similar to this.

CREATE FUNCTION roomSplit (@roomCode VARCHAR(MAX), @separator VARCHAR(10))
RETURNS VARCHAR(MAX)
AS  
BEGIN 
    DECLARE @res VARCHAR(MAX)
    
    SELECT @res = STUFF((
        SELECT
        ', ' + roomNameColumn
        FROM
        STRING_SPLIT(@roomCode, @separator) AS SPLIT
        INNER JOIN roomTable AS R ON SPLIT.value = R.roomCodeColumn
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
    
    RETURN @res
END

Then you call function that you have created by filling parameters with your data and your separator data.

SELECT dbo.roomSplit('203,201', ',')

Let’s hope it can and does.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading