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 insert a line break after every second loop in t-sql stuff function

how can i insert a CHAR(10) after every second loop in t-sql stuff function in my query

  SELECT  STUFF(
                (
                    SELECT  ', ' + new_name 
                   FROM new_subcatagories
                   FOR XML PATH(''), TYPE
                ).value('.', 'VARCHAR(MAX)'), 1, 2, '')

so the result should by

record1,record2,

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

record3,record4

>Solution :

You could use a CASE expression to see if the value of ROW_NUMBER is divisible by 2, and if not then add a carriage return and line break:

SELECT STUFF((SELECT CASE WHEN ROW_NUMBER() OVER (order by new_nam) % 2 = 1 THEN CHAR(13) + CHAR(10) ELSE '' END + ', ' + new_nam
              FROM new_subcatagories
              ORDER BY new_nam
              FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 4, '');
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