Back to all posts

Insert <br> tag in SQL text string

CREATE or ALTER FUNCTION dbo.Fn_InserBRtag(@inputString NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @resultString NVARCHAR(MAX) = ''; DECLARE @st…

SQL
CREATE or ALTER FUNCTION dbo.Fn_InserBRtag(@inputString NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN 
DECLARE @resultString NVARCHAR(MAX) = '';
DECLARE @startIndex INT = 1;
DECLARE @chunkSize INT = 50;
DECLARE @chunk NVARCHAR(MAX);
 
IF LEN(@inputString) > 0
BEGIN
    WHILE @startIndex <= LEN(@inputString)
    BEGIN
        SET @chunk = SUBSTRING(@inputString, @startIndex, @chunkSize);
        DECLARE @lastSpaceIndex INT = CHARINDEX(' ', REVERSE(LEFT(@chunk, @chunkSize )));
        IF @lastSpaceIndex = 0
        BEGIN
            SET @resultString = @resultString + @chunk + '<br>';
            SET @startIndex = @startIndex + @chunkSize;
        END
        ELSE
        BEGIN
            SET @resultString = @resultString + LEFT(@chunk, @chunkSize - @lastSpaceIndex) + '<br>';
            SET @startIndex = @startIndex + @chunkSize - @lastSpaceIndex + 1;
        END
    END
END
 
Return @resultString;
END
 
GO
 
SELECT dbo.Fn_InserBRtag('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.')

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.