数字の表がまだない場合:
SET NOCOUNT ON;
DECLARE @UpperLimit INT;
SET @UpperLimit = 4000;
WITH n(rn) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_columns
)
SELECT [Number] = rn - 1
INTO dbo.Numbers FROM n
WHERE rn <= @UpperLimit + 1;
CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers([Number]);
区切られた文字列をセットに変換する一般的な分割関数:
CREATE FUNCTION dbo.SplitString
(
@List NVARCHAR(MAX),
@Delim CHAR(1)
)
RETURNS TABLE
AS
RETURN ( SELECT
rn,
vn = ROW_NUMBER() OVER (PARTITION BY [Value] ORDER BY rn),
[Value]
FROM
(
SELECT
rn = ROW_NUMBER() OVER (ORDER BY CHARINDEX(@Delim, @List + @Delim)),
[Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM dbo.Numbers
WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], 1) = @Delim
) AS x
);
GO
そして、それらを元に戻す関数:
CREATE FUNCTION dbo.DedupeString
(
@List NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN ( SELECT newval = STUFF((
SELECT '\' + x.[Value] FROM dbo.SplitString(@List, '\') AS x
WHERE (x.vn = 1)
ORDER BY x.rn
FOR XML PATH, TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
);
END
GO
使用例:
SELECT dbo.DedupeString('alpha\bravo\bravo\charlie\delta\bravo\charlie\delta');
結果:
alpha\bravo\charlie\delta
次のように言うこともできます:
UPDATE dbo.MessedUpTable
SET OopsColumn = dbo.DedupeString(OopsColumn);
@MikaelEriksson はおそらく、XML を使用して重複を排除するためのより効率的な方法で急襲するでしょうが、それはそれまで私が提供できるものです。 :-)