この関数を使用して値を分割します。
CREATE FUNCTION [dbo].[udfSplitCSV]
(
@String varchar (max),
@Delimiter varchar (10) = ','
)
RETURNS @ValueTable TABLE ([Row] int IDENTITY(1,1), [Value] varchar(max), [Length] int, [Duplicate] int NULL)
BEGIN
DECLARE @NextString varchar(max)
DECLARE @Pos int
DECLARE @NextPos int
IF @String IS NULL RETURN
--Initialize
SET @NextString = ''
SET @String = @String + @Delimiter
--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1
--Loop while there is still a comma in the String
WHILE (@Pos <> 0)
BEGIN
SET @NextString = RTrim(LTrim(SubString(@String,1,@Pos - 1)))
INSERT INTO @ValueTable ([Value], [Length]) VALUES (@NextString, Len(@NextString))
SET @String = SubString(@String,@Pos+1,Len(@String))
SET @NextPos = @Pos
SET @Pos = CharIndex(@Delimiter,@String)
END
UPDATE @ValueTable
SET [Duplicate] = X.Duplicate
FROM @ValueTable VT
INNER JOIN (Select [Row], [Value], Row_Number() OVER (Partition By [Value] ORDER BY [Value], [Row]) as Duplicate FROM @ValueTable) X
ON X.[Row] = VT.[Row]
RETURN
END
-- Select * from dbo.udfSplitCSV('a , c b,c, a', ',')