Split function equivalent in T-SQL?

后端 未结 15 1823
深忆病人
深忆病人 2020-11-21 07:23

I’m looking to split \'1,2,3,4,5,6,7,8,9,10,11,12,13,14,15...\' (comma delimited) into a table or table variable.

Does anyone have a function that returns each one

15条回答
  •  温柔的废话
    2020-11-21 07:48

    CREATE FUNCTION Split
    (
      @delimited nvarchar(max),
      @delimiter nvarchar(100)
    ) RETURNS @t TABLE
    (
    -- Id column can be commented out, not required for sql splitting string
      id int identity(1,1), -- I use this column for numbering splitted parts
      val nvarchar(max)
    )
    AS
    BEGIN
      declare @xml xml
      set @xml = N'' + replace(@delimited,@delimiter,'') + ''
    
      insert into @t(val)
      select
        r.value('.','varchar(max)') as item
      from @xml.nodes('//root/r') as records(r)
    
      RETURN
    END
    GO
    

    usage

    Select * from dbo.Split(N'1,2,3,4,6',',')
    

提交回复
热议问题