Solved

Getting certain data from a string

Posted on 2016-11-08
1
23 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:
ScottPletcher 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Would coalesce be what I use here and, if so, how? 8 41
SQL Select Query help 3 31
sql server query? 6 26
Test a query 23 15
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 …
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

705 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now