How to split a comma-separated value to columns

后端 未结 30 4051
刺人心
刺人心 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:54

    Try this (change instances of ' ' to ',' or whatever delimiter you want to use)

    CREATE FUNCTION dbo.Wordparser
    (
      @multiwordstring VARCHAR(255),
      @wordnumber      NUMERIC
    )
    returns VARCHAR(255)
    AS
      BEGIN
          DECLARE @remainingstring VARCHAR(255)
          SET @remainingstring=@multiwordstring
    
          DECLARE @numberofwords NUMERIC
          SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)
    
          DECLARE @word VARCHAR(50)
          DECLARE @parsedwords TABLE
          (
             line NUMERIC IDENTITY(1, 1),
             word VARCHAR(255)
          )
    
          WHILE @numberofwords > 1
            BEGIN
                SET @word=LEFT(@remainingstring, CHARINDEX(' ', @remainingstring) - 1)
    
                INSERT INTO @parsedwords(word)
                SELECT @word
    
                SET @remainingstring= REPLACE(@remainingstring, Concat(@word, ' '), '')
                SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)
    
                IF @numberofwords = 1
                  BREAK
    
                ELSE
                  CONTINUE
            END
    
          IF @numberofwords = 1
            SELECT @word = @remainingstring
          INSERT INTO @parsedwords(word)
          SELECT @word
    
          RETURN
            (SELECT word
             FROM   @parsedwords
             WHERE  line = @wordnumber)
    
      END
    

    Example usage:

    SELECT dbo.Wordparser(COLUMN, 1),
           dbo.Wordparser(COLUMN, 2),
           dbo.Wordparser(COLUMN, 3)
    FROM   TABLE
    

提交回复
热议问题