How Do I Split a Delimited String in SQL Server Without Creating a Function?

前端 未结 11 1731
慢半拍i
慢半拍i 2020-11-29 08:28

I\'m working with a SQL Server database. I have a column which contains a delimited list, and I need to write a query which splits the values of the list into rows. From bro

11条回答
  •  臣服心动
    2020-11-29 09:00

    A version using XML.

    declare @S varchar(100) = 'Hello John Smith'
    
    select 
      n.r.value('.', 'varchar(50)')
    from (select cast(''+replace(@S, ' ', '')+'' as xml)) as s(XMLCol)
      cross apply s.XMLCol.nodes('r') as n(r)
    

    Using a table instead Replace @T with what ever table you are using.

    -- Test table
    declare @T table (ID int, Col varchar(100))
    insert into @T values (1, 'Hello John Smith')
    insert into @T values (2, 'xxx yyy zzz')
    
    select 
      T.ID,
      n.r.value('.', 'varchar(50)')
    from @T as T
      cross apply (select cast(''+replace(replace(Col,'&','&'), ' ', '')+'' as xml)) as S(XMLCol)
      cross apply S.XMLCol.nodes('r') as n(r)
    

    Splitting the string 'Hello John Smith' without using a variable

    select 
      n.r.value('.', 'varchar(50)')
    from (select cast(''+replace('Hello John Smith', ' ', '')+'' as xml)) as s(XMLCol)
      cross apply s.XMLCol.nodes('r') as n(r)
    

提交回复
热议问题