Home Forums SQL Server 2008 T-SQL (SS2K8) Append characters in a sentence after certain length RE: Append characters in a sentence after certain length

  • SET ANSI_NULLS ON

    GO

    SET QUOTED_IDENTIFIER ON

    GO

    Create FUNCTION String_Insert ( @String VARCHAR(MAX) )

    RETURNS VARCHAR(MAX)

    AS

    BEGIN

    DECLARE @i INT= 0

    DECLARE @x INT= 0

    DECLARE @max-2 INT = LEN(LTRIM(RTRIM(@String)))

    DECLARE @REV VARCHAR(32)

    SET @i = 32;

    WHILE @i <= @max-2

    BEGIN

    IF SUBSTRING(@String, @i, 1) = ' '

    BEGIN

    SET @String = STUFF(@String, @i, 0, '|')

    END

    ELSE

    BEGIN

    SET @x = CHARINDEX(' ',

    REVERSE(SUBSTRING(@String, 1, @i)))

    SET @i = @i - @x + 2;

    SET @String = STUFF(@String, @i, 0, '|')

    END

    SET @i = @i + 32;

    END

    -- Return the result of the function

    RETURN @String

    END

    GO

    Here I created a temp table and tested on it.

    IF object_ID('tempDB..#temp') IS NOT NULL

    DROP TABLE #temp

    CREATE TABLE #temp

    (

    String VARCHAR(200)

    )

    INSERT #temp (String) VALUES ( 'ABCDEFGH IJKLMNOPQRS TUVWXYZ ABCDEFGHIJKLMN OPQRSTUVWXYZA BCDEFGHIJKLMNOP'

    ),('ABCDEFGH IJKLMNOPQRS TUVWXYZ ABCDEFGHIJKLMN OPQRSTUVWXYZAB CDEFGHIJKLMNOP')

    SELECT String_Insert(String) FROM #temp

    Thanks to my friend Lakshmi who helped me in writing the code.This is one way of doing it! Hope it works.