mercredi 2 décembre 2015

Inserting extra rows into a result set based on the data length of a text column

Because of a bug in my reporting tool (Rave reports) which causes errors with text columns that contain more than X characters i need to break some rows in a result set into extra rows. Say I have a table called transactions like:

CREATE TABLE Trans
    (id int, type int, description varchar(55), memo text)
;

INSERT INTO Trans
    (id, type, description, memo)
VALUES
    (1, 1,  'blah', 'hi there'),
    (2, 100, 'foobar', 'yawn'),
    (3, 700, 'emailmessage', 'This some long text that needs to broken into chunks. This some long text that needs to broken into chunks. This some long text that needs to broken into chunks. '),
    (4, 1,   'blah blah blah', 'some other text')
;

Look at the third row, it has approx 160 chars, and lets say I want to break row 3 into 4 extra rows each with a chunk of no more than 50 chars each of the long memo. The final result of the query would be the same structure as the Trans table but now with 7 rows. The ID column should be renumbered to reflect the extra rows. I need it for SQL Server 2005.

Of course the extra rows would each have a different chunk of the long memo in the correct order but their other column values would be copies of the values in the original row

I know I could use a cursor to do it but I'm looking for better way.

The result set for this example and a chunk size of 50 chars should look like this:

id    type  description     memo
----- ----- --------------- -------------------------------------------------
1     1     blah            hi there
2     100   foobar          foobar
3     700   emailmessage    This some long text that needs to broken into chu
4     700   emailmessage    nks. This some long text that needs to broken int
5     700   emailmessage    o chunks. This some long text that needs to broke
6     700   emailmessage    n into chunks.
7     1     blah blah blah  some other text

Make the chunk length a variable that I can alter. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire