SQL Split Function and Ordering Issue?

后端 未结 5 1131
小鲜肉
小鲜肉 2021-01-18 03:53

I have the following Split function,

ALTER FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))     
                returns @tempt         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 04:23

    A simpler function:

    CREATE FUNCTION dbo.SplitStrings_Ordered
    (
        @List       nvarchar(MAX),
        @Delimiter  nvarchar(255)
    )
    RETURNS TABLE
    AS
    RETURN 
    (
      SELECT [Index] = CHARINDEX(@Delimiter, @List + @Delimiter, Number),
             Item = SUBSTRING(@List, Number, CHARINDEX(@Delimiter, 
                    @List + @Delimiter, Number) - Number)
        FROM 
        (
          SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects
        ) AS n(Number)
        WHERE Number <= CONVERT(INT, LEN(@List))
        AND SUBSTRING(@Delimiter + @List, Number, LEN(@Delimiter)) = @Delimiter
    );
    GO
    

    Sample usage:

    DECLARE @s nvarchar(MAX) = N',around the home,clean and protect,soaps and air'
      + ' fresheners,air fresheners';
    
    SELECT Item FROM dbo.SplitStrings_Ordered(@s, N',') ORDER BY [Index];
    

    Or to return orders from a table ordered by input:

    SELECT o.OrderID
      FROM dbo.Orders AS o
      INNER JOIN dbo.SplitStrings_Ordered('123,789,456') AS f
      ON o.OrderID = CONVERT(int, f.Item)
      ORDER BY f.[Index];
    

提交回复
热议问题