SQL SERVER 一行按照某个由分隔符拼接的字段拆分成多行

创建函数
CREATE FUNCTION [dbo].[UF_SplitStringToTable](
    @sInputList VARCHAR(MAX) -- List of delimited items
  , @sDelimiter VARCHAR(20) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(50))

BEGIN
DECLARE @sItem VARCHAR(MAX)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
查询语句
SELECT 
   [Id],i.item as keyword  
FROM table
OUTER APPLY UF_SplitStringToTable(table.Keywords, ',') i
THE END