I have a table with the following field containing values like:
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
130,123,140 1,2,3 45FS-d,54,56 120 2134 1000,2000,3000
How do I obtain the following values without pulling my hair out?
130 1 45 120 2134 1000
It's easy if your database has the right built-in functions.
Here's the solution for Microsoft SQL Server:
select case when patindex('%[^0-9]%',thefield) > 0 then left(thefield, patindex('%[^0-9]%',thefield) - 1 ) else thefield end as thesubstring from thetable
In this example, the PATINDEX function searches the field for the pattern [^0-9] which means any character except 0 through 9. PATINDEX returns the position of the first occurrence. Thus, if PATINDEX finds a non-numeric, subtract 1 to get the length of the numeric substring, and use that in the LEFT function. If PATINDEX does not find a non-numeric, it returns 0, so in that case, use the entire field.
If instead of SQL Server you have some other database system, then your mileage, as they say, may vary.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.