Create function to split delimited seperated data for all records in the table [duplicate]

。_饼干妹妹 提交于 2019-12-02 08:32:37

You can choose a string splitting function from Aaron Bertrand's Split strings the right way – or the next best way, and use it with cross apply to select the data from your table. For this demonstration I've chosen to go with the XML string split function.
So first, create the function:

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

Then all you need to do is something like this:

SELECT ID, Item
FROM TABLE
CROSS APPLY
dbo.SplitStrings_XML(FIELD, ',')

See a live demo on rextester.

Also,you should probably read Is storing a delimited list in a database column really that bad?, where you will see a lot of reasons why the answer to this question is Absolutely yes!

You should XML With CROSS APPLY no need Explicit Function :

SELECT ID,
       split.a.value('.', 'NVARCHAR(MAX)') [FIELD]
FROM
(
    SELECT ID,
           CAST('<M>'+REPLACE([Field], ',', '</M><M>')+'</M>' AS XML) AS String
    FROM #TM
) AS a
CROSS APPLY String.nodes('/M') AS split(a);

Result :

ID FIELD
1  A
1  B
1  C
1  D
2  X
2  Y
2  Z
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!