SQL Server Join In Order

后端 未结 3 1734
礼貌的吻别
礼貌的吻别 2021-01-12 07:55

I have 2 string in input for example \'1,5,6\' and \'2,89,9\' with same number of element (3 or plus). Those 2 string i want made a \"ordinate join\" as

1           


        
3条回答
  •  忘掉有多难
    2021-01-12 08:44

    Thanks to Arion's suggestion. It's very useful for me. I modified the function a little bit to support varchar(max) type of input string, and max length of 1000 for the delimiter string. Also, added a parameter to indicate if you need the empty string in the final return.

    For MatBailie's question, because this is an inline function, you can include the pn column in you outer query which is calling this function.

    CREATE FUNCTION dbo.Split (@s nvarchar(max),@sep nvarchar(1000),  @IncludeEmpty bit)
    RETURNS table
    AS
    RETURN (
        WITH Pieces(pn, start, stop) AS (
          SELECT convert(bigint, 1) , convert(bigint, 1), convert(bigint,CHARINDEX(@sep, @s))
          UNION ALL
          SELECT pn + 1, stop + LEN(@sep), CHARINDEX(@sep, @s, stop + LEN(@sep))
          FROM Pieces
          WHERE stop > 0
        )
        SELECT pn,
          SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE LEN(@s) END) AS s
        FROM Pieces
        where start< CASE WHEN stop > 0 THEN stop ELSE LEN(@s) END + @IncludeEmpty
      )
    

    But I ran into a bit issue with this function when the list intended to return had more than 100 records. So, I created another function purely using string parsing functions:

    Create function [dbo].[udf_split] (
        @ListString nvarchar(max),
        @Delimiter  nvarchar(1000),
        @IncludeEmpty bit) 
    Returns @ListTable TABLE (ID int, ListValue varchar(max))
    AS
    BEGIN
        Declare @CurrentPosition int, @NextPosition int, @Item nvarchar(max), @ID int
        Select  @ID = 1,
                @ListString = @Delimiter+ @ListString + @Delimiter,
                @CurrentPosition = 1+LEN(@Delimiter)
    
        Select  @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
        While   @NextPosition > 0 Begin
    
            Select  @Item = Substring(@ListString, @CurrentPosition, @NextPosition-@CurrentPosition)
            If      @IncludeEmpty=1 or Len(LTrim(RTrim(@Item)))>0 Begin 
                    Insert Into @ListTable (ID, ListValue) Values (@ID, LTrim(RTrim(@Item)))
                    Set @ID = @ID+1
            End
            Select  @CurrentPosition = @NextPosition+LEN(@Delimiter), 
                    @NextPosition = Charindex(@Delimiter, @ListString, @CurrentPosition)
        End
        RETURN
    END
    

    Hope this could help.

提交回复
热议问题