Split a string with no delimiters into columns

后端 未结 5 1295
清歌不尽
清歌不尽 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 12:55

    One way

    declare @str varchar(max) = 'ABCDE'
    declare @sql nvarchar(max) = ''
    declare @i int = 1
    while (@i <= len(@str)) begin
        set @sql += case when @i > 1 then ',' else '' end + '''' + substring(@str, @i, 1) + ''''
        set @i += 1 
    end
    
    exec('select ' + @sql)
    

    (If ' can appear as a char you would need to substitute '')

提交回复
热议问题