Split a string with no delimiters into columns

后端 未结 5 1299
清歌不尽
清歌不尽 2021-01-26 12:40

I need to split a string in a column into one character each into it\'s own column in SQL Server 2012.

Example: if I have a column with \'ABCDE\', I need to

5条回答
  •  感情败类
    2021-01-26 13:18

    I am interpreting the question as putting the characters into one column ("split a string in a column into one character each into it's own column"). However, I realize that this might be ambiguous.

    One method is with a recursive CTE:

    with chars as (
          select left(val, 1) as c, substring(val, 2, len(val)) as rest
          from (select 'ABCDE' as val union all select '123') t
          union all
          select left(rest, 1), substring(rest, 2, len(rest))
          from chars
          where rest <> ''
         )
    select c
    from chars;
    

    Just plug in your table and column in the subquery. Note that you might want to include other columns as well.

    Here is a SQL Fiddle.

    If you want multiple columns and the number is not fixed, then you will need dynamic SQL.

提交回复
热议问题