Position within String (INSTR or LOCATE() ?)

  • I have a field which has postcodes

    What I would like to be able to do is find the Alphabetic part of the postcode

    my idea was to look at the first four characters of the field and then find the position of the first number

    eg

    Data In : TW11 7PR

    SELECT LEFT('TW11 7PR',4)

    TW11

    But now I need to fidn the position of the first numberic and return only TW

    A= Represents A-Z

    #= REpresents 0-9

    The data is in these formats

    AA## #AA

    A# #AA

    AA#A #AA

    A## #AA

    A# ##A

    your help would be appreciated guys, Im using Query Analyzer 2000

     

     

     

     

     

     

  • Something like this?

    DECLARE @a VARCHAR(20)

    SET @a = 'TW11 7PR'

    SELECT LEFT(@a,PATINDEX('%[0-9]%',@a)-1)

    SET @a = 'TESTME_All OVER11 7PR'

    SELECT LEFT(@a,PATINDEX('%[0-9]%',@a)-1)

                        

    --------------------

    TW

    (1 row(s) affected)

                        

    --------------------

    TESTME_All OVER

    (1 row(s) affected)

     

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • LOL Thanks Frank

    I just got my answer before I checked your post, what I did was

     

    SELECT case

    when patindex('%[0-9]%',ADR.ZIPCODE) > 0

    then left(ADR.ZIPCODE,patindex('%[0-9]%',ADR.ZIPCODE)-1)

    else ADR.ZIPCODE

    end          as prefix

     

    I was really looking forward to answering my own post

    Thanks for your help though

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply