• Many thanks for your anwers.

    I tried the two different approaches from dwain.c with my sample table with 100k nvarchar(50) strings. On my machine with Win 8 64, SQL Server 2012, Core i7 2.4 Ghz and 16 GB RAM the second version without LAG function took around 5 seconds. The first version with LAG executed for 12 minutes when I aborted it!! Slight difference...

    With the other three approaches I have to admit that I can't get it to work with my sample table. How can I incorporate a column from my table into the code instead of the @code parameter?

    Anyway, I think the 5 seconds will be hard to beat.