Answered Query zip codes with extra digits

  • quarta-feira, 29 de agosto de 2012 14:58
     
     

    Hi,

    If my database stores zipcode without being separated by a '-' after the first 5 zip code, how can i pull a query for zip code in 300xx-23xx?

    Percentage symbol doesn't work in this case :(

Todas as Respostas

  • quinta-feira, 30 de agosto de 2012 08:06
     
      Contém Código

    This depends on the used SQL Server version. When you're using SQL Server 2012 it's pretty simple. Use the new TRY_CAST() function:

    DECLARE @Sample TABLE ( ZipCode NVARCHAR(255) );
    
    INSERT  INTO @Sample
    VALUES  ( 'a' ),
            ( '1000' ),
            ( '2300' ),
            ( '2500' ),
            ( '3000' );
    
    SELECT  *
    FROM    @Sample
    WHERE   TRY_CAST(ZipCode AS INT) BETWEEN 2300 AND 3000;

    Otherwise you can use ISNUMERIC:

    SELECT  *
    FROM    @Sample
    WHERE   ISNUMERIC(ZipCode) = 1
            AND CAST(CAST(ZipCode AS VARCHAR(255)) AS INT) BETWEEN 2300 AND 3000;

    The CAST(ZipCode AS VARCHAR(255)) is only necessary when the ZipCode field is NVARCHAR.


  • quinta-feira, 30 de agosto de 2012 09:39
    Moderador
     
     Respondido

    Hi Sammeh00,

    If the format of the zipcode is fixed, you can fomart the zip code using T-SQL like below:

    Select
    SUBSTRING(zipcode,1,5)+'-'+ SUBSTRING(zipcode,6,4) From TableName

    Please feel free to let me know if you have any question.

    Thanks,
    Eileen

    TechNet Subscriber Support

    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.

  • quinta-feira, 30 de agosto de 2012 09:48
     
      Contém Código

    When you want a match on "300xx-23xx" then use:

    DECLARE @Sample TABLE ( ZipCode NVARCHAR(255) );
    
    INSERT  INTO @Sample
    VALUES  ( '1234512345' ),
            ( '300002300' );
    
    SELECT  *
    FROM    @Sample
    WHERE   ZipCode LIKE '300__23__';

  • segunda-feira, 17 de setembro de 2012 20:46
     
     
    Thank you ! I will try both suggestions !