Writing a WordWrap Function in SQL Server

Hello everyone,

In this article, I will try to give information about writing a WordWrap function in SQL Server.

In SQL Server you may need a function like WordWrap in some cases. WordWrap cuts a text to a certain length and displays the remainder on a new line. This is how the process goes.

You can easily do this using the function below.

CREATE FUNCTION [dbo].[WrapText]
(
    @Metin NVARCHAR(MAX),
    @Uzunluk INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @Sonuc AS NVARCHAR(MAX);
    SELECT @Sonuc = CASE
                        WHEN @Sonuc IS NULL THEN
                            SUBSTRING(@Metin, numara.Numara - @Uzunluk + 1, @Uzunluk)
                        ELSE
                            @Sonuc + CHAR(13) + CHAR(10) + SUBSTRING(@Metin, numara.Numara - @Uzunluk + 1, @Uzunluk)
                    END
    FROM
    (
        SELECT Numara = ROW_NUMBER() OVER (ORDER BY name)
        FROM sys.all_objects
    ) numara
    WHERE numara.Numara <= LEN(@Metin) + @Uzunluk - 1
          AND numara.Numara % @Uzunluk = 0;
    RETURN @Sonuc;
END;

--Use of Function

PRINT dbo.WrapText('abcdefghijklmnopqrstuvwxyz',5)

When you create the above function and run the code, you will see a result similar to the one below.

As you can see, the entered text has been cut to a certain length and passed to the bottom line.

Good luck to everyone in business and life.

18 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!