拆分字符串爲單一字符

以下面這個樣子:ide

 

本函式是學習使用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能夠修改一下:spa

 

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

 

再來看看執行的結果:code

相關文章
相關標籤/搜索