How Stuff and 'For Xml Path' work in Sql Server

后端 未结 9 1520
盖世英雄少女心
盖世英雄少女心 2020-11-21 13:49

Table is:

+----+------+
| Id | Name |
+----+------+    
| 1  | aaa  |
| 1  | bbb  |
| 1  | ccc  |
| 1  | ffffd  |
| 1  | eee  |
+----+------+

9条回答
  •  误落风尘
    2020-11-21 14:24

    PATH mode is used in generating XML from a SELECT query

    1. SELECT   
           ID,  
           Name  
    FROM temp1
    FOR XML PATH;  
    
    Ouput:
    
    1
    aaa
    
    
    
    1
    bbb
    
    
    
    1
    ccc
    
    
    
    1
    ffffd
    
    
    
    1
    eee
    
    

    The Output is element-centric XML where each column value in the resulting rowset is wrapped in an row element. Because the SELECT clause does not specify any aliases for the column names, the child element names generated are the same as the corresponding column names in the SELECT clause.

    For each row in the rowset a tag is added.

    2.
    SELECT   
           ID,  
           Name  
    FROM temp1
    FOR XML PATH('');
    
    Ouput:
    1
    aaa
    1
    bbb
    1
    ccc
    1
    ffffd
    1
    eee
    

    For Step 2: If you specify a zero-length string, the wrapping element is not produced.

    3. 
    
        SELECT   
    
               Name  
        FROM temp1
        FOR XML PATH('');
    
        Ouput:
        aaa
        bbb
        ccc
        ffffd
        eee
    
    4. SELECT   
            ',' +Name  
    FROM temp1
    FOR XML PATH('')
    
    Ouput:
    ,aaa,bbb,ccc,ffffd,eee
    

    In Step 4 we are concatenating the values.

    5. SELECT ID,
        abc = (SELECT   
                ',' +Name  
        FROM temp1
        FOR XML PATH('') )
    FROM temp1
    
    Ouput:
    1   ,aaa,bbb,ccc,ffffd,eee
    1   ,aaa,bbb,ccc,ffffd,eee
    1   ,aaa,bbb,ccc,ffffd,eee
    1   ,aaa,bbb,ccc,ffffd,eee
    1   ,aaa,bbb,ccc,ffffd,eee
    
    
    6. SELECT ID,
        abc = (SELECT   
                ',' +Name  
        FROM temp1
        FOR XML PATH('') )
    FROM temp1 GROUP by iD
    
    Ouput:
    ID  abc
    1   ,aaa,bbb,ccc,ffffd,eee
    

    In Step 6 we are grouping the date by ID.

    STUFF( source_string, start, length, add_string ) Parameters or Arguments source_string The source string to modify. start The position in the source_string to delete length characters and then insert add_string. length The number of characters to delete from source_string. add_string The sequence of characters to insert into the source_string at the start position.

    SELECT ID,
        abc = 
        STUFF (
            (SELECT   
                    ',' +Name  
            FROM temp1
            FOR XML PATH('')), 1, 1, ''
        )
    FROM temp1 GROUP by iD
    
    Output:
    -----------------------------------
    | Id        | Name                |
    |---------------------------------|
    | 1         | aaa,bbb,ccc,ffffd,eee |
    -----------------------------------
    

提交回复
热议问题