Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Verwenden eines CTE, um Ergebnisse über ein CROSS APPLY aufzuteilen

Vielleicht suchen Sie nach so etwas (es ist eine vereinfachte Version, ich habe nur den Vornamen und das Kommentardatum als "Bezeichner" verwendet). Ich habe es mit diesen Daten getestet und - im Moment - die maximale Länge von 50 abgebildet, um die Textspalte zu teilen. Tipp:Ändern Sie den Datentyp comment_text in VARCHAR(500)

DECLARE @Comments TABLE
(
    id INT NOT NULL IDENTITY PRIMARY KEY CLUSTERED,
    comment_date DATETIME NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    comment_title VARCHAR(50) NOT NULL,
    comment_text VARCHAR(500)
);

    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Bob', 'Example','Bob''s Comment', 'Text of Bob''s comment.');
    INSERT INTO @Comments VALUES(CURRENT_TIMESTAMP, 'Alice', 'Example','Alice''s Comment'
    , 'Text of Alice''s comment that is much longer and will need to be split over multiple rows aaaaaa bbbbbb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff ggggggggggggg.');

WITH CTE AS (SELECT comment_date, first_name, '<Note>'+CAST( SUBSTRING(comment_text, 1, 50) AS VARCHAR(500)) +'</Note>'comment_text, 1 AS RN
             FROM @Comments 
             UNION ALL 
             SELECT A.comment_date, A.first_name, '<Text>'+CAST( SUBSTRING(A.comment_text, B.RN*50+1, 50) AS VARCHAR(500)) +'</Text>'AS comment_text, B.RN+1 AS RN
             FROM @Comments A 
             INNER JOIN CTE B ON A.comment_date=B.comment_date AND A.first_name=B.first_name 
            WHERE  LEN(A.comment_text) > B.RN*50+1                    
             )
SELECT A.comment_date, A.first_name, '<title>'+ comment_title+'</title>' AS markup  
FROM @Comments A
UNION ALL
SELECT B.comment_date, B.first_name, B.comment_text AS markup  
FROM  CTE B ;

Ausgabe:

    comment_date        first_name  markup
2017-07-07 14:30:51.117 Bob         <title>Bob's Comment</title>
2017-07-07 14:30:51.117 Alice       <title>Alice's Comment</title>
2017-07-07 14:30:51.117 Bob          <Note>Text of Bob's comment.</Note>
2017-07-07 14:30:51.117 Alice        <Note>Text of Alice's comment that is much longer and wi</Note>
2017-07-07 14:30:51.117 Alice        <Text>ll need to be split over multiple rows aaaaaa bbbb</Text>
2017-07-07 14:30:51.117 Alice        <Text>bb cccccc ddddddddddd eeeeeeeeeeee fffffffffffff g</Text>
2017-07-07 14:30:51.117 Alice        <Text>gggggggggggg.</Text>