码迷,mamicode.com
首页 > 数据库 > 详细

1 SQL SERVER 实现字符串分割成table的方法

时间:2017-08-29 13:01:40      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:substr   begin   where   实现   position   pos   create   entity   ret   

CREATE FUNCTION [dbo].[fn_SplitStringToTable]
(
    @p_Input     VARCHAR(MAX),
    @p_Delimeter CHAR(1) = ,
)
RETURNS @l_Table TABLE
(
    Id       INT IDENTITY(1, 1),
    Value    VARCHAR(511),
    Position INT,
    Length   INT
)

BEGIN
   DECLARE @l_Position INT,
           @l_Value    VARCHAR(256)
   
   SELECT @l_Position = 1,
          @l_Value = ‘‘
   
   IF RIGHT(@p_Input, LEN(@p_Delimeter)) <> @p_Delimeter
      SET @p_Input = @p_Input + @p_Delimeter
   
   WHILE SUBSTRING(@p_Input, @l_Position, 1) = CHAR(10) OR
        SUBSTRING(@p_Input, @l_Position, 1) = CHAR(13)
   BEGIN
      SELECT @l_Position = @l_Position + 1
   END
   
   WHILE @l_Position <= CHARINDEX(@p_Delimeter, @p_Input, @l_Position)
   BEGIN
      SET @l_Value = RTRIM ( LTRIM ( SUBSTRING ( @p_Input,
                                                 @l_Position,
                                                 CHARINDEX ( @p_Delimeter,
                                                             @p_Input,
                                                             @l_Position) - @l_Position ) ) )
      
      IF NOT EXISTS ( SELECT 1
                        FROM @l_Table
                       WHERE Value = @l_Value )
      BEGIN
         INSERT INTO @l_Table ( Value, Position, Length )
              VALUES ( @l_Value, @l_Position, CHARINDEX ( @p_Delimeter,
                                                          @p_Input,
                                                          @l_Position ) - @l_Position )
      END
      
      SELECT @l_Position = CHARINDEX(@p_Delimeter, @p_Input, @l_Position) + 1
      
      WHILE SUBSTRING(@p_Input, @l_Position, 1) = CHAR(10) OR
         SUBSTRING(@p_Input, @l_Position, 1) = CHAR(13)
      BEGIN
         SELECT @l_Position = @l_Position + 1
      END
   END
   RETURN
END

 

1 SQL SERVER 实现字符串分割成table的方法

标签:substr   begin   where   实现   position   pos   create   entity   ret   

原文地址:http://www.cnblogs.com/mibing/p/7447234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!