Search code examples
htmlsqlsql-servertemplatesgenerate

Creating html content with SQL


I am using Microsoft SQL Server 2016. I can use it in another version.

I have variables of an html page content in my tables.

SQL Server tables:

PageVariables
Menus
Slides etc.

Can I generate page html in SQL Server without programming?

I tried to do it with Replace partially. But it doesn't work on multi-line tables. I don't think this is the right way either.

Is there something like SQL Server in javascript like mustache, vue, javascript literal?

declare @template nvarchar(max)='<html><head>{title}</title></head><body><div class="menu">{menu}</div></body></html>'

declare @title  nvarchar(max)='My Page'
declare @menu  nvarchar(max)=''

SELECT 'My Menu-1' AS 'MenuName',
       '?link=1' AS 'MenuLink'
UNION ALL
SELECT 'My Menu-2' AS 'MenuName',
       '?link=2' AS 'MenuLink'

/*
for @menu
    set @menu='<a href="@MenuLink">@MenuName</a>'
next
*/
SET @template = REPLACE(@template, '{title}', @title)
SET @template = REPLACE(@template, '{menu}', @menu)

SELECT @template

it is also difficult in this way.

        SELECT '?link=1' AS '@href',
               'My Menu-1' AS 'span'

        UNION ALL
        SELECT '?link=2' AS '@href',
               'My Menu-2' AS 'span'

        FOR XML PATH ('a'), ROOT ('div')


Solution

  • What you are looking to do is one of these string concatenation operations when you have multiple rows that you need to combine into single entry:

    1. Concatenate Multiple Rows Using FOR XML PATH
    2. Concatenate Rows Using COALESCE
    3. Using STRING_AGG