简体   繁体   English

使用sql提取字符串的一部分

[英]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 请参阅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 请参阅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))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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