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.