简体   繁体   中英

Extracting part of a string using sql

I have a string which is of the form

Text I Want to Discard (TEXT I WANT)

I only want the part of the string contained in brackets. How do I go about getting this substring?

How about this:

select substring(col, charindex('(', col), len(col))  
from yourtable;

See SQL Fiddle with Demo

Or check for both brackets. This gets the location of the opening bracket ( and then returns the length of the string between the opening and closing bracket:

select substring(col, charindex('(', col), charindex(')', col) - charindex('(', col) +1)
from yourtable;

See SQL Fiddle with Demo

Try the below... it works...

DECLARE @c varchar(100)
SET     @c = 'Text I Want to Discard (TEXT I WANT)' 
SET @c = Replace(Replace(@c,')','_'),'(','_');
SELECT SUBSTRING(
    @c, 
    CHARINDEX('_', @c) + 1, 
    LEN(@c) - CHARINDEX('_', @c) - CHARINDEX('_', REVERSE(@c))
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM