Home Forums SQL Server 2008 SQL Server 2008 - General I need help with my query. I found part of this, but doesn't work. Please help. RE: I need help with my query. I found part of this, but doesn't work. Please help.

  • Instead of write-only code, I've always found it immensely helpful to split up complex string manipulations for readability into individual parts using cascading CROSS APPLYs like this:

    ;WITH Notes (Note) AS (

    SELECT 'aaa abc@wondwerks.com bbb'

    UNION ALL SELECT 'dwain.c@sqlservercentral.com'

    UNION ALL SELECT 'dwain.c@'

    UNION ALL SELECT '@sqlservercentral.com'

    UNION ALL SELECT 'aaa @sqlservercentral.com'

    UNION ALL SELECT '@')

    SELECT email

    FROM Notes

    CROSS APPLY (SELECT CHARINDEX('@', Note)) a (PosOfAt)

    CROSS APPLY (

    SELECT SUBSTRING(Note, 1, PosOfAt - 1)

    ,SUBSTRING(Note, PosOfAt + 1, LEN(Note))) b(Leading, Trailing)

    CROSS APPLY (

    SELECT REVERSE(LEFT(REVERSE(Leading), CHARINDEX(' ', REVERSE(Leading) + ' ') - 1)) + '@' +

    LEFT(Trailing, CHARINDEX(' ', Trailing + ' ') - 1)) c(email)

    WHERE LEFT(email, 1) <> '@' AND RIGHT(email, 1) <> '@'

    If you can apply this to your Notes field, you should be able to find only email addresses that contain text on both sides of the @.

    Alternatively, you can also use a PATINDEX to isolate only the valid email addresses like this:

    ;WITH Notes (Note) AS (

    SELECT 'aaa abc@wondwerks.com bbb'

    UNION ALL SELECT 'dwain.c@sqlservercentral.com'

    UNION ALL SELECT 'dwain.c@'

    UNION ALL SELECT '@sqlservercentral.com'

    UNION ALL SELECT 'aaa @sqlservercentral.com'

    UNION ALL SELECT '@')

    SELECT Note

    FROM Notes

    WHERE Note LIKE '%[0-9A-Za-z.][@][0-9A-Za-z.]%'

    You'll probably need to add in a few characters to the left [0-9A-Za-z.], like underscore (_), etc. to include all possible valid email address characters.


    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