Solved

SQL pull numeric from string

Posted on 2011-03-14
15
469 Views
Last Modified: 2012-06-21
I need to be able to pull the zip code out for either example

'5220 michaux rd,greensboro,n.c.27410' or '5220 michaux rd,greensboro,n.c.27410-9203'

How?
0
Comment
Question by:cheryl9063
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +3
15 Comments
 
LVL 22

Expert Comment

by:8080_Diver
ID: 35133372
Do you know for sure that the ZIP Code will be the characters after the last space in the string?
Do you only want the 5 digit Zip Code or do you want the full 9 digit if it is available?
-- SQL_1 - as many Zip Code Characters as are available
SELECT RIGHT(yourstring, CHARINDEX(' ', REVERSE(yourstring) - 1)) AS ZipCode
FROM yourtable;

-- SQL_2 - only the 5 digit Zip Code
SELECT LEFT(RIGHT(yourstring, CHARINDEX(' ', REVERSE(yourstring) - 1)), 5) AS ZipCode
FROM yourtable;

Open in new window

0
 
LVL 9

Expert Comment

by:sshah254
ID: 35133383
Let's assume that this data is in field1

reverse(field1)
find the first "." (or comma, or space, whatever tells that the zip code is starting) in there
charindex(reverse(field1))
right(field1, len(field1) - charindex(reverse(field1))) should give you what you want

You may need to add +1 or subtract -1 ... don't remember if MSSQL does it with 0-index or not.

Ss

0
 
LVL 50

Accepted Solution

by:
Lowfatspread earned 125 total points
ID: 35133401
like this....

select case when zipstr like '%-%' then left(zipstr,charindex('-',zipstr)-1) else zipstr end as zip
  from (
select reverse(left(rcol,charindex('.',rcol)-1)) as zipstr
  from (select yourcolumn as col,reverse(yourcolumn) as rcol
          from ....) as x
       ) as y
0
Comparison of Amazon Drive, Google Drive, OneDrive

What is Best for Backup: Amazon Drive, Google Drive or MS OneDrive? In this free whitepaper we look at their performance, pricing, and platform availability to help you decide which cloud drive is right for your situation. Download and read the results of our testing for free!

 
LVL 1

Author Comment

by:cheryl9063
ID: 35133476
LowfatSpread..What is rcol and what is "Your column?" This is not coming from a table.. This is a variable passed in that I'm having to unparse..
0
 
LVL 41

Expert Comment

by:Sharath
ID: 35133860
Create a function like this.
CREATE FUNCTION [dbo].[fn_Split](@text nvarchar(max), @delimiter char(1) = ' ')
RETURNS @Strings TABLE (position int IDENTITY PRIMARY KEY, value nvarchar(max)) AS 
  BEGIN 
DECLARE @index int
    SET @index = -1
  WHILE (LEN(@text) > 0)
  BEGIN
    SET @index = CHARINDEX(@delimiter , @text)
     IF (@index = 0) AND (LEN(@text) > 0)
  BEGIN 
 INSERT INTO @Strings VALUES (@text)
  BREAK 
    END
     IF (@index > 1)
  BEGIN
 INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
    SET @text = RIGHT(@text, (LEN(@text) - @index))
    END 
   ELSE 
    SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
 RETURN
    END
 GO

Open in new window

Use this function in your code as below.Replace your_table with the actual table name and PostalAddress column with actual column name.
SELECT PostalAddress,value zip  
  FROM (SELECT *, 
               ROW_NUMBER() 
                 OVER(PARTITION BY PostalAddress ORDER BY position DESC) rn 
          FROM your_table t 
               CROSS APPLY dbo.fn_Split(PostalAddress,'.')) t1 
 WHERE rn = 1

Open in new window

I have tested like this.
DECLARE  @table  TABLE( 
                       PostalAddress VARCHAR(100) 
                       ) 

INSERT @table 
VALUES('5220 michaux rd,greensboro,n.c.27410'), 
      ('5220 michaux rd,greensboro,n.c.27410-9203') 

SELECT PostalAddress,value zip  
  FROM (SELECT *, 
               ROW_NUMBER() 
                 OVER(PARTITION BY PostalAddress ORDER BY position DESC) rn 
          FROM @table t 
               CROSS APPLY dbo.fn_Split(PostalAddress,'.')) t1 
 WHERE rn = 1
/*
PostalAddress	zip
5220 michaux rd,greensboro,n.c.27410	27410
5220 michaux rd,greensboro,n.c.27410-9203	27410-9203
*/

Open in new window

0
 
LVL 1

Author Comment

by:cheryl9063
ID: 35134356
There is no table... Will any of these work for a variable input such as below..

@Location = 5220 michaux rd greensboro n.c.27410

@NEEdZip =  
0
 
LVL 41

Assisted Solution

by:Sharath
Sharath earned 125 total points
ID: 35135180
Yes, you can try like this.

SELECT @NEEdZip = value  
  FROM (SELECT *, 
               ROW_NUMBER() 
                 OVER(PARTITION BY PostalAddress ORDER BY position DESC) rn 
          FROM (select @Location as PostalAddress) t 
               CROSS APPLY dbo.fn_Split(PostalAddress,'.')) t1 
 WHERE rn = 1
select @NEEdZip

Open in new window

0
 
LVL 32

Expert Comment

by:awking00
ID: 35139418
Can address also be like this?
'5220 Michaux Rd., Greensboro, NC 27410'
0
 
LVL 22

Expert Comment

by:8080_Diver
ID: 35139982
Yes,

Create a function and, in the function, set the output/result to "RIGHT(yourstring, CHARINDEX(' ', REVERSE(yourstring) - 1)) " where yourstring is the string passed into the function as the parameter.
0
 
LVL 22

Assisted Solution

by:8080_Diver
8080_Diver earned 125 total points
ID: 35140004
Using the variables you previously indicated:

@NEEdZip = RIGHT(@Location, CHARINDEX(' ', REVERSE(@Location) - 1))

You don't have to create the function (but, just so I could use it elsewhere ;-) I would. ;-)
0
 
LVL 32

Expert Comment

by:awking00
ID: 35140123
Without knowing the data, I'm not sure I would count on either a period introducing the zip code or the last space introducing the zip code. Are there any other examples for the input?
0
 
LVL 1

Author Comment

by:cheryl9063
ID: 35140201
awKing..that is the problem.. Could be any kind of address with either a 5 digit of the extended american 9 digit with dash.. The state could be spelled out or not, could be dots.. I'm having to just "TRY" each and pass a successful one to an outside process that validates.. If it does not validate I come back and "try" again 5 times.. My problem is the one I mentioned at the top with n.c...
0
 
LVL 41

Expert Comment

by:Sharath
ID: 35140438
<< Could be any kind of address with either a 5 digit of the extended american 9 digit with dash.. The state could be spelled out or not, could be dots.. >>

Provide sample data for all these combinations. BTW, did you try my last query?
0
 
LVL 32

Assisted Solution

by:awking00
awking00 earned 125 total points
ID: 35140742
Try this -
substr(address,regexp_instr(addr,'[0-9]{5}|[0-9]{5}-[0-9]{4}'))
0
 
LVL 1

Author Closing Comment

by:cheryl9063
ID: 35169119
Thanks
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question