【问题标题】:I need a function in sql server to insert a space in each postion of an input string我需要 sql server 中的一个函数在输入字符串的每个位置插入一个空格
【发布时间】:2012-01-22 23:37:52
【问题描述】:

我需要 sql server 中的一个函数在输入字符串的每个位置插入一个空格。 例如,如果函数的输入是

"example"

函数的输出应该是

word1   word2
e       xample
ex      ample
exa     mple
exam    ple
examp   le
exampl  e

【问题讨论】:

  • 这看起来在应用程序代码中做得更好。
  • 我会和 Oded 一样回答。这是可能的,我认为。但不是我会用 (T-)SQL 做的事情。

标签: sql sql-server string tsql split


【解决方案1】:
declare @S varchar(20) = 'example'

select left(@S, number) as word1,
       stuff(@S, 1, number, '') as word2
from master..spt_values
where type = 'P' and
      number between 1 and len(@S)-1

如果你想要一列插入空格,或者像这样:

select stuff(@S, number, 0, ' ') as word
from master..spt_values
where type = 'P' and
      number between 2 and len(@S)      

【讨论】:

    【解决方案2】:

    试试这个:

    CREATE FUNCTION dbo.SplitString(@Input VARCHAR(100))
    RETURNS @tblStringSplitted TABLE 
    (
        -- Columns returned by the function
        word1 VARCHAR(100),
        word2 VARCHAR(100)
    )
    AS 
    BEGIN
        DECLARE @IX INT
        DECLARE @MAX INT
    
        SET @IX = 2
        SET @MAX = LEN(@Input)
    
        WHILE (@IX <= @MAX)
        BEGIN
            INSERT INTO @tblStringSplitted(word1, word2)
            VALUES(
                SUBSTRING(@Input, 1, @IX-1),
                SUBSTRING(@Input, @IX, @MAX-@IX+1)
            )       
            SET @IX = @IX + 1
        END
    
        RETURN;
    END;
    GO
    

    称它为:

    SELECT * FROM dbo.SplitString('example')
    

    将返回:

    word1     word2
    e         xample
    ex        ample
    exa       mple
    exam      ple
    examp     le
    exampl    e
    

    【讨论】:

      【解决方案3】:

      @Oded 是对的 - 作为一般规则,这种事情最好在应用程序代码中完成。

      话虽如此,尝试一下总是很有趣。以下函数将处理您想要的:

      CREATE FUNCTION dbo.SplitString(@input VARCHAR(MAX))
      RETURNS @splits table (word1 varchar(MAX), word2 varchar(MAX))
      AS
      BEGIN
      
      ;WITH Numbers ( n ) AS (
          SELECT 1 UNION ALL
          SELECT 1 + n FROM Numbers WHERE n < LEN(@input)-1 )
      INSERT @splits
      SELECT
          word1 = SUBSTRING(@input,1,n),
          word2 = SUBSTRING(@input,n+1,LEN(@Input) - n)
      FROM Numbers
      OPTION ( MAXRECURSION 0 )
      
      RETURN
      
      END
      

      调用使用:

      select * from dbo.SplitString('example')
      

      【讨论】:

        猜你喜欢
        • 2012-05-19
        • 2020-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 2020-04-22
        • 2011-08-18
        相关资源
        最近更新 更多