Extracting part of a string using sql

☆樱花仙子☆ 提交于 2020-01-05 04:23:46

问题


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?


回答1:


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




回答2:


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))
)


来源:https://stackoverflow.com/questions/14503909/extracting-part-of-a-string-using-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!