T-SQL Split Word into characters

前端 未结 5 1172
太阳男子
太阳男子 2020-11-28 12:19

I have searched everywhere and I cannot find this implementation anywhere.

Let\'s say I have the word: QWERTY

I want to obtain this table:

5条回答
  •  时光取名叫无心
    2020-11-28 12:40

    Here is a table-valued function (derived from aF's temp table implementation). It differs slightly from aF's implementation in that it starts with @count=1; this excludes an extraneous leading space.

    CREATE FUNCTION [dbo].[Chars] (@string VARCHAR(max)) 
    RETURNS @chars TABLE (character CHAR) 
    AS 
      BEGIN 
          DECLARE @count INT, 
                  @total INT 
    
          SELECT @total = Len(@string), 
                 @count = 1 
    
          WHILE @count <= @total 
            BEGIN 
                INSERT INTO @chars 
                SELECT Substring(@string, @count, 1) 
    
                SELECT @count = @count + 1 
            END 
    
          RETURN 
      END 
    

    Usage:

    SELECT * FROM dbo.chars('QWERTY AnotherWord')
    

提交回复
热议问题