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

Convert space seperated values of a column to single column in sql server

I have a column with values as mentioned below.

Transaction_ID
GT980 FR563
BR923 DE498 QS347
HB743

How can I convert and bring the results like below. I need to split the value with space delimiter. Any suggestions on how this can be achieved.

 Transaction_ID
   GT980 
   FR563
   BR923 
   DE498 
   QS347
   HB743

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 :

Create a Split string function in sql.

CREATE FUNCTION fnSplitString
( 
  @string VARCHAR(MAX), 
  @delimiter VARCHAR(MAX) 
) 
RETURNS @output TABLE(splitdata VARCHAR(MAX)) 
BEGIN 

  DECLARE @Xml XML

  SET @Xml = CAST(('<a>'+REPLACE(@string,@delimiter,'</a><a>')+'</a>') AS XML)

  INSERT INTO @output (splitdata)
    SELECT ltrim(rtrim(A.value('.', 'VARCHAR(MAX)')))  FROM @Xml.nodes('a') AS FN(a)

  RETURN 
END

and then use it as

select cs.* 
from yourtable
cross apply fnSplitString (Transaction_ID, ' ') cs
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