How to parse a string and create several columns from it?

后端 未结 4 1648
半阙折子戏
半阙折子戏 2020-12-19 10:33

I have a varchar(max) field containing Name Value pairs, in every line I have Name UnderScore Value.

I need to do a query against it so that it returns

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 11:15

    He is an example that you can use:

    -- Creating table:
    create table demo (dID int, dRec varchar(100));
    
    -- Inserting records:
    insert into demo (dID, dRec) values (1, 'BCQP1 Sam');
    insert into demo (dID, dRec) values (2, 'BCQP2 LD');
    
    -- Selecting fields to retrive records:
    select * from demo;
    

    Then I want to show in one single row both rows combined and display only the values from the left removing the name on the right side up to the space character.

        /*
        The STUFF() function puts a string in another string, from an initial position.  
        The LEFT() function returns the left part of a character string with the specified number of characters. 
        The CHARINDEX() string function returns the starting position of the specified expression in a character string. 
    */
    SELECT 
     DISTINCT
       STUFF((SELECT ' ' + LEFT(dt1.dRec, charindex(' ', dt1.dRec) - 1) 
              FROM demo dt1
              ORDER BY dRec
              FOR XML PATH('')), 1, 1, '') [Convined values]
    FROM demo dt2
    --
    GROUP BY dt2.dID, dt2.dRec
    ORDER BY 1
    

    As you can see here when you run the function the output will be:

    BCQP1 BCQP2
    

    On the top of the script I explained what each function is used for (STUFF(), LEFT(), CHARINDEX() functions) I also used DISTINCT in order to eliminate duplicate values.

    NOTE: dt stands for "demo table", I used the same table and use two alias dt1 and dt2, and dRec stands for "demo Record"

    If you want to learn more about STUFF() Function here is a link:

    https://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/

提交回复
热议问题