With a SQL function, how do I take a delimited string and return it as HTML elements?

StackOverflow https://stackoverflow.com/questions/23553952

  •  18-07-2023
  •  | 
  •  

Вопрос

If I have a DataField that consists of:

Red|Blue|Green|Orange|Black

I'd like to create a function that returns this as a single dynamic variable [Colors] and when rendered it looks like this:

<li>Red</li>
<li>Blue</li>
<li>Green</li>
<li>Orange</li>
<li>Black</li>

So I need to generate the li elements, just as they are above, all within SQL.

I've done this the other way around using STUFF, where I can create this when the values are individual items in a table.

Any help would be appreciated.

Thank you!

Это было полезно?

Решение

This should do it:

DECLARE @xml as xml
DECLARE @string as varchar(100)

SET @string ='Red|Blue|Green|Orange|Black'
SET @xml = cast( ('<li>' + replace( @string, '|' ,'</li><li>') + '</li>') as xml)

SELECT @xml
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top