Solved

Getting certain data from a string

Posted on 2016-11-08
1
44 Views
Last Modified: 2016-11-08
I have a string in the DB

"JRSJC2LPValueSummary(122012)pdf(1179185).pdf"  

I need to get the number between the ().  If there is more than one set of (), like in this example, then I need the number from the 2nd set of ().

1179185

I can get the first set by using this:

substring([FileName], charindex('(', [FileName]) + 1, charindex(')', [FileName]) - charindex('(', [FileName]) - 1) AS DocumentNumberParsed

I don't know how to get the 2nd set IF there is a 2nd set.

I appreciate any help.
0
Comment
Question by:huerita37
1 Comment
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 41879577
SELECT [FileName], SUBSTRING([FileName], FileName_Lparen_Final + 1,
    CHARINDEX(')', STUFF([FileName], 1, FileName_Lparen_Final + 1, ''))) AS FileNameNumber
FROM (
    VALUES('JRSJC2LPValueSummary(122012)pdf(1179185).pdf'),
                  ('JRSJC2LPValueSummary(122012).pdf')
) AS test_data([FileName])
CROSS APPLY (
    SELECT CHARINDEX('(', [FileName]) AS FileName_Lparen1
) AS ca1
CROSS APPLY (
    SELECT CHARINDEX('(', [FileName], FileName_Lparen1 + 1) AS FileName_Lparen2
) AS ca2
CROSS APPLY (
    SELECT CASE WHEN FileName_Lparen2 > 0 THEN FileName_Lparen2 ELSE FileName_Lparen1 END AS FileName_Lparen_Final
) AS ca3
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

805 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