sql >> Database >  >> RDS >> Sqlserver

Een CTE gebruiken om resultaten te splitsen over een CROSS APPLY

Misschien ben je op zoek naar iets als dit (het is een vereenvoudigde versie, ik gebruikte alleen de voornaam en comment_date als "identifier"). Ik heb het getest met behulp van deze gegevens en - voor het moment - beeldvorming van max len 50 om de tekstkolom te splitsen. Tip:verander comment_text datatype 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 ;

Uitgang:

    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>


  1. Mysql -- Laatste 30 dagen

  2. Geld overboeken tussen accountID in MySQL

  3. Een alfabetpiramide afdrukken in PL/SQL

  4. SQL-vergelijkingsoperator