拆分字符串为单一字符

如下面这个样子:

 

本函式是学习使用WHILE以及SUBSTRING的应用:

 

CREATE FUNCTION [dbo].[svf_SplitStringToSingleCharacter](
  @DataSource NVARCHAR(4000)
)
RETURNS NVARCHAR(4000)
AS
BEGIN
   DECLARE @rtvResult NVARCHAR(4000),@length INT       

   SET @length = lEN(ISNULL(@DataSource,'')) 
   
   IF @length = 0
      SET @rtvResult = N''
   ELSE
   BEGIN
        WHILE @length > 0
        BEGIN
            SET @rtvResult = ISNULL(@rtvResult + ',',N'') + '''' + SUBSTRING(@DataSource,@length,1) + ''''
            SET @length = @length - 1
        END
   END
     
   RETURN @rtvResult
END
Source Code

 
上面的自定义的函数,在执行之后所得到的结果,并没有按照输入的顺序排列。

那Insus.NET可以修改一下:

 

CREATE FUNCTION [dbo].[svf_SplitStringToSingleCharacter1](
  @DataSource NVARCHAR(4000)
)
RETURNS NVARCHAR(4000)
AS
BEGIN
   DECLARE @rtvResult NVARCHAR(4000),@length INT       

   SET @length = lEN(ISNULL(@DataSource,'')) 
   
   IF @length = 0
      SET @rtvResult = N''
   ELSE
   BEGIN
        DECLARE @i INT = 1
        WHILE @i <= @length
        BEGIN
            SET @rtvResult =  ISNULL(@rtvResult + ',',N'') + ''''  +  SUBSTRING(@DataSource,1,1) + ''''
            SET @DataSource = STUFF(@DataSource,1,1,N'')
            SET @i = @i + 1
        END
   END
     
   RETURN @rtvResult
END
GO
Source Code

 

再来看看执行的结果:

posted @ 2018-11-18 13:00  Insus.NET  阅读(1043)  评论(0编辑  收藏  举报