CREATE FUNCTION PMX_SplitTextIntoThreeColumns(
    @InputText NVARCHAR(MAX), @MXLen int
)
RETURNS @Data TABLE
(
        Col1 NVARCHAR(500),
        Col2 NVARCHAR(500),
        Col3 NVARCHAR(500)
)
AS
BEGIN

	DECLARE @Col1 NVARCHAR(500);
    DECLARE @Col2 NVARCHAR(500);
    DECLARE @Col3 NVARCHAR(500);

    -- Initialize variables
    DECLARE @RemainingText NVARCHAR(MAX) = LTRIM(RTRIM(@InputText));
    DECLARE @CurrentPart NVARCHAR(500);
    DECLARE @SpaceIndex INT;

    -- Function to get a substring that fits within @MXLen characters without splitting a word
    SET @Col1 = NULL;
    SET @Col2 = NULL;
    SET @Col3 = NULL;

    -- Loop to fill each column
    IF LEN(@RemainingText) > 0
    BEGIN
        -- Get the first part
        IF LEN(@RemainingText) <= @MXLen
        BEGIN
            SET @Col1 = @RemainingText;
            SET @RemainingText = '';
        END
        ELSE
        BEGIN
            SET @CurrentPart = LEFT(@RemainingText, @MXLen);
            SET @SpaceIndex = CHARINDEX(' ', REVERSE(LEFT(@CurrentPart, @MXLen)));
            IF @SpaceIndex > 0
                SET @Col1 = LEFT(@CurrentPart, @MXLen - @SpaceIndex + 1);
            ELSE
                SET @Col1 = LEFT(@CurrentPart, @MXLen);
            SET @RemainingText = LTRIM(SUBSTRING(@RemainingText, LEN(@Col1) + 1, LEN(@RemainingText)));
        END
    END

    IF LEN(@RemainingText) > 0
    BEGIN
        -- Get the second part
        IF LEN(@RemainingText) <= @MXLen
        BEGIN
            SET @Col2 = @RemainingText;
            SET @RemainingText = '';
        END
        ELSE
        BEGIN
            SET @CurrentPart = LEFT(@RemainingText, @MXLen);
            SET @SpaceIndex = CHARINDEX(' ', REVERSE(LEFT(@CurrentPart, @MXLen)));
            IF @SpaceIndex > 0
                SET @Col2 = LEFT(@CurrentPart, @MXLen - @SpaceIndex + 1);
            ELSE
                SET @Col2 = LEFT(@CurrentPart, @MXLen);
            SET @RemainingText = LTRIM(SUBSTRING(@RemainingText, LEN(@Col2) + 1, LEN(@RemainingText)));
        END
    END

    IF LEN(@RemainingText) > 0
    BEGIN
        -- Get the third part
        IF LEN(@RemainingText) <= @MXLen
        BEGIN
            SET @Col3 = @RemainingText;
            SET @RemainingText = '';
        END
        ELSE
        BEGIN
            SET @CurrentPart = LEFT(@RemainingText, @MXLen);
            SET @SpaceIndex = CHARINDEX(' ', REVERSE(LEFT(@CurrentPart, @MXLen)));
            IF @SpaceIndex > 0
                SET @Col3 = LEFT(@CurrentPart, @MXLen - @SpaceIndex + 1);
            ELSE
                SET @Col3 = LEFT(@CurrentPart, @MXLen);
            SET @RemainingText = LTRIM(SUBSTRING(@RemainingText, LEN(@Col3) + 1, LEN(@RemainingText)));
        END
    END

	INSERT INTO @Data
		select @Col1, @Col2, @Col3

	RETURN
END
