Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

sql server - Find and Remove Repeated Substrings

I've a column in a SQL Server 2008 table where part of the string was accidentally repeated.

Does anyone have a quick and easy way to remove the trailing duplicated substring?

For example,

alpharavocharliedeltacharliedelta

should be

alpharavocharliedelta
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't already have a numbers table:

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]);

Now a generic split function, that will turn your delimited string into a set:

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

And then a function that puts them back together:

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

Sample usage:

SELECT dbo.DedupeString('alpharavoravocharliedeltaravocharliedelta');

Results:

alpharavocharliedelta

You can also say something like:

UPDATE dbo.MessedUpTable
  SET OopsColumn = dbo.DedupeString(OopsColumn);

@MikaelEriksson will probably swoop in with a more efficient way to use XML to eliminate duplicates, but that is what I can offer until then. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...