SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Parse a fixed length numeric value from a string

By Glen Potter,

Specifically, I needed to parse a zip code (5-digit) from a client comments fields where the number was in different positions such as "Customer 999999999 should be at zip code 99999" and "99999 zipcode" and "should be zip code 99999 phone 9999999999".

My stored procedure first filters on a [Comments] field string that contains variations of the phrase/word "zip code" (ie., "WHERER [Comments] Like '%zip code%'" OR "[Comments] Like '%zipcode%'"). I then needed a function to parse the string just for the 5-digit number. Of course this will break out and return only the first 5-digit number.

I also wanted to keep the function multi-purpose so I used a "intDigits" parm so it could be used for other fixed-length numbers. This could easily be omitted, but then would also need to return multiple numbers
(ie., "Customer 999999999 should be at zip code 99999" would need to return arg1 = 999999999, and arg2 = 99999) ...
or to call another function based on another function parsing for the location of the first numeric char in the string Substring({str},{lastcharpos} + Len(arg1)) = {nextcharpos} etc....

...which is another script altogether.

Total article views: 444 | Views in the last 30 days: 1
Related Articles

How to get unused numbers from 1 to 99999

How to get unused numbers from 1 to 99999


Format Phone Number function

Function to format phone numbers entered as text.


Remove SQL Comments

This function takes in SQL code and returns the same SQL code but with any comments removed (i.e. "/...


A simple trick for “Block Comment” syntax in SSMS

Make your comment blocks much more useful, in a surprising number of ways


Function to get number of days in month

Function to get number of days in month

sqlinsider scripts