How to split a comma-separated value to columns

后端 未结 30 4050
刺人心
刺人心 2020-11-21 04:38

I have a table like this

Value   String
-------------------
1       Cleo, Smith

I want to separate the comma delimited string into two colu

30条回答
  •  醉梦人生
    2020-11-21 04:57

    I think PARSENAME is the neat function to use for this example, as described in this article: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/

    The PARSENAME function is logically designed to parse four-part object names. The nice thing about PARSENAME is that it’s not limited to parsing just SQL Server four-part object names – it will parse any function or string data that is delimited by dots.

    The first parameter is the object to parse, and the second is the integer value of the object piece to return. The article is discussing parsing and rotating delimited data - company phone numbers, but it can be used to parse name/surname data also.

    Example:

    USE COMPANY;
    SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
    

    The article also describes using a Common Table Expression (CTE) called ‘replaceChars’, to run PARSENAME against the delimiter-replaced values. A CTE is useful for returning a temporary view or result set.

    After that, the UNPIVOT function has been used to convert some columns into rows; SUBSTRING and CHARINDEX functions have been used for cleaning up the inconsistencies in the data, and the LAG function (new for SQL Server 2012) has been used in the end, as it allows referencing of previous records.

提交回复
热议问题