• OK, so the purists will argue that LAG is overkill, and for them I offer this instead:

    WITH SampleData AS

    (

    SELECT code=CAST('12333345566689333' AS NVARCHAR(4000))

    UNION ALL SELECT '12333345566689'

    ),

    Tally (n) AS

    (

    SELECT TOP (4000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

    FROM sys.all_columns

    ),

    SplitString AS

    (

    SELECT code, s, n

    FROM

    (

    SELECT code, n, s=SUBSTRING(code, n, 1)

    FROM SampleData a

    CROSS APPLY

    (

    SELECT TOP (LEN(code)) n

    FROM Tally

    ) b

    WHERE SUBSTRING(code, n, 1) <> SUBSTRING(code, n-1, 1)

    ) a

    )

    SELECT code

    ,ReducedString=

    (

    SELECT s + ''

    FROM SplitString b

    WHERE a.code = b.code

    ORDER BY n

    FOR XML PATH('')

    )

    FROM SampleData a;


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St