• Thanks for the awesome feedback, John. I really appreciate it.

    Thanks for including an explanation, as well. I normally try to explain the code for the OP in the form of embedded comments, but it was getting late and I got a bit lazy. You covered it for me very nicely.

    As a sidebar, perhaps we can make one small optimization that probably won't matter unless there are millions of rows at hand... it'll also give me a chance to redeem myself for being so lazy last night...

    [font="Courier New"]--===== Create and populate a test table.

         -- This is NOT a part of the solution.

    DECLARE @Address TABLE (Address CHAR(50))

     INSERT INTO @Address

            (Address)

     SELECT 'Lincoln' UNION ALL

     SELECT 'Kentucky Kentucky' UNION ALL

     SELECT 'Walla Walla' UNION ALL

     SELECT 'New York New York' UNION ALL

     SELECT 'New York CITY New York CITY' UNION ALL

     SELECT 'New York CITYNew York CITY' UNION ALL

     SELECT 'New York CITYNew York CITY       ' UNION ALL

     SELECT 'Ohio' UNION ALL

     SELECT 'Iowa'

     

    --===== Return only single addresses.

         -- If you compare the left half of the string to the right half

         -- and both halves are the same, then use just the left half.

         -- If the halves are not the same, then the address has not been

         -- doubled up and we can use the address as it is.

    --

         -- Notice that each half can be either separated by a space or 

         -- jammed together (see test data above) when a dupe is present.  

         -- The divide by 2 in the code below works in either case because

         -- LEN() procudes an INT and the 2 is an INT which forces only 

         -- Integer math to take place.  For example, if your string is

         -- "AB AB" or "ABAB", the length of one half for the first is

         -- 5/2 = 2 and 4/2 = 2 for the second. Both equal 2 in integer math.

         -- The cool part about LEN() is that it won't count trailing spaces

         -- so no special calculation for CHAR(50) needs to be made.  We do,

         -- however, have to RTRIM() the RIGHT side of the address when we

         -- split the address in half so we don't pick up on any trailing

         -- spaces.

     SELECT CASE    

            WHEN LEFT(Address,LEN(Address)/2RIGHT(RTRIM(Address),LEN(Address)/2)    

            THEN LEFT(Address,LEN(Address)/2)        

            ELSE Address         

            END AS SingleAddress

       FROM @Address[/font]

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)