Skip to content
Advertisement

Add class and onclick function to HTML string from SQL Server

I’ve a query string to create HTML row

SELECT (
    SELECT 'Court 1' as th, 'Court 2' as th, 'Court 3' as th, 'Court 4' as th 
    FOR XML raw('tr'), ELEMENTS, TYPE
) AS headertr

and the output is

<tr><th>Court 1</th><th>Court 2</th><th>Court 3</th><th>Court 4</th></tr>

Is there any way to add an onclick function and class from SQL itself?

Advertisement

Answer

It’s unclear where you want the attributes to go, but you could do something like this

SELECT (
    SELECT
      'myfunction()' AS [th/@onclick],
      'SomeClass' AS [th/@class],
      th
    from (VALUES
      ('Court 1'),
      ('Court 2'),
      ('Court 3'),
      ('Court 4')
    ) v(th)
    FOR XML PATH(''), ROOT('tr'), TYPE
) AS headertr

db<>fiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement