Breakdown text into multiple records

Raj D 591 Reputation points
2025-02-03T06:27:58.5266667+00:00

Greetings...

I'm working on a SQL Server query where I have to breakdown text stored in Comments column which is of datatype varchar(max) into multiple records.
For instance, if there are 280000 characters in the Comments column then it should be broken down into 5 parts part 1; 1-64750 characters, part 2; 64751 - 129500 characters, part 3; 129501 - 194250 characters, part 4; 194251 - 259000 characters and the last remaining part 4; 259001 - 280000 characters to be broken down into 5 parts part 1; 1-64750 characters, part 2; 64751 - 129500 characters, part 3; 129501 - 194250 characters, part 4; 194251 - 259000 characters and the last remaining part 4; 259001 - 280000 characters. So, the expected output should look like below.

Query:
SQL Query

When I run my query I get only one record with PartId 1 but not the rest. Unable to figure out what I'm missing.
Expected Output:

Id PartId CommentPart
1 1 From Character 1 - 64750 characters
1 2 From Character 64751 - 129500 characters
1 3 From Character 129501 - 194250 characters
1 4 From Character 194251 - 259000 characters
1 5 From Character 259001 - 280000 characters

Thank you in advance.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,437 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,689 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 119.7K Reputation points
    2025-02-03T09:34:59.83+00:00

    Fix the INSERT statement and re-try your script:

    INSERT INTO #CommentsTable (ID, Comments)
    VALUES (1, REPLICATE(cast('A' as varchar(max)), 280000));
    

    Also try an alternative:

    ;
    with Q as
    (
    	select ID, PartID = 1, CommentPart = substring(Comments, 1, @ChunkSize), i = @ChunkSize + 1
    	from #CommentsTable
    	union all
    	select c.ID, PartID + 1, substring(c.Comments, i, @ChunkSize), i + @ChunkSize
    	from #CommentsTable c
    	inner join Q on Q.ID = c.ID
    	where i <= len(c.Comments)
    )
    select ID, PartID, CommentPart 
    from Q
    order by ID, PartID
    option (maxrecursion 0)
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.