SQL Server Join In Order

后端 未结 3 1723
礼貌的吻别
礼貌的吻别 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:47

    You can do it like this as well

    Consider your split function like this:

    CREATE FUNCTION Split
    (
      @delimited nvarchar(max),
      @delimiter nvarchar(100)
    ) RETURNS @t TABLE
    (
      id int identity(1,1),
      val nvarchar(max)
    )
    AS
    BEGIN
      declare @xml xml
      set @xml = N'' + replace(@delimited,@delimiter,'') + ''
    
      insert into @t(val)
      select 
        r.value('.','varchar(5)') as item
      from @xml.nodes('//root/r') as records(r)
    
      RETURN
    END
    GO
    

    The it will be a simple task to JOIN them together. Like this:

    SELECT
        *
    FROM
        dbo.Split('1,5,6',',') AS a
        JOIN dbo.Split('2,89,9',',') AS b
            ON a.id=b.id
    

    The upside of this is that you do not need any ROW_NUMBER() OVER(ORDER BY SELECT 0)

    Edit

    As in the comment the performance is better with a recursive split function. So maybe something like this:

    CREATE FUNCTION dbo.Split (@s varchar(512),@sep char(1))
    RETURNS table
    AS
    RETURN (
        WITH Pieces(pn, start, stop) AS (
          SELECT 1, 1, CHARINDEX(@sep, @s)
          UNION ALL
          SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
          FROM Pieces
          WHERE stop > 0
        )
        SELECT pn,
          SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
        FROM Pieces
      )
    GO
    

    And then the select is like this:

    SELECT
        *
    FROM
        dbo.Split('1,5,6',',') AS a
        JOIN dbo.Split('2,89,9',',') AS b
            ON a.pn=b.pn
    

提交回复
热议问题