如果字段中有多个括号,如何在 SQL 到 return 中仅使用括号内包含的字段的右侧部分?
How do I use SUBSTRING and CHARINDEX in SQL to return only the right part of a field contained within brackets if multiple brackets are in the field?
我有一列包含 varchar 数据的数据,我一直在尝试 return 使用 CHARINDEX 和 SUBSTRING 仅 return 包含括号的部分:
列数据:'this is an (example)'
我用下面的代码从上面的数据中return'example':
SELECT SUBSTRING (column, CHARINDEX('(', column)+1 , CHARINDEX(')', column)- CHARINDEX('(', column)-1 )
这工作正常,但是,在某些情况下,字段中的数据在两个括号之间多次出现数据:
- 'this (is) an (example)'
这意味着我上面的代码 returns 'is'。在我的数据中,我要return的是最右边一组括号中的数据:
- 'this (is) an (example)' - 我想要 return 'example'
- 'this (is) some (text)' - 我想要 return 'text'
- 'this (is) definitely (not) a (number)' - 我想要 return 'number'
等
在您的所有示例中,最后一个字符是 )
。如果这总是正确的,那么最简单的方法可能是:
select replace(stuff(v.str, 1, len(v.str) - charindex('(', reverse(v.str)) - 1, ''), ')', '')
from (values ('this (is) definitely (not) a (number)')) v(str);
更通用的解决方案是:
select v.str,
replace(stuff(v2.str, 1, len(v2.str) - charindex('(', reverse(v2.str) + '(') + 1, ''), ')', '')
from (values ('this (is) definitely (not) a (number)'),
('this (is) definitely (not) a (number) alas'),
('no parens')
) v(str) cross apply
(values (left(v.str, len(v.str) - charindex(')', reverse(v.str) + ')') + 1))) v2(str);
这也是一种方法:
这是 DEMO
select reverse(
substring(
reverse(str_col)
, CHARINDEX(')', reverse(str_col))+1
, CHARINDEX('(', reverse(str_col))-2
)
)
from test;
如果 text/number 本身不包含 (
或 )
,这也应该有效
select replace(reverse(left(reverse(str_col), charindex('(', reverse(str_col)) -1)),')','')
from test;
我有一列包含 varchar 数据的数据,我一直在尝试 return 使用 CHARINDEX 和 SUBSTRING 仅 return 包含括号的部分:
列数据:'this is an (example)'
我用下面的代码从上面的数据中return'example':
SELECT SUBSTRING (column, CHARINDEX('(', column)+1 , CHARINDEX(')', column)- CHARINDEX('(', column)-1 )
这工作正常,但是,在某些情况下,字段中的数据在两个括号之间多次出现数据:
- 'this (is) an (example)'
这意味着我上面的代码 returns 'is'。在我的数据中,我要return的是最右边一组括号中的数据:
- 'this (is) an (example)' - 我想要 return 'example'
- 'this (is) some (text)' - 我想要 return 'text'
- 'this (is) definitely (not) a (number)' - 我想要 return 'number'
等
在您的所有示例中,最后一个字符是 )
。如果这总是正确的,那么最简单的方法可能是:
select replace(stuff(v.str, 1, len(v.str) - charindex('(', reverse(v.str)) - 1, ''), ')', '')
from (values ('this (is) definitely (not) a (number)')) v(str);
更通用的解决方案是:
select v.str,
replace(stuff(v2.str, 1, len(v2.str) - charindex('(', reverse(v2.str) + '(') + 1, ''), ')', '')
from (values ('this (is) definitely (not) a (number)'),
('this (is) definitely (not) a (number) alas'),
('no parens')
) v(str) cross apply
(values (left(v.str, len(v.str) - charindex(')', reverse(v.str) + ')') + 1))) v2(str);
这也是一种方法: 这是 DEMO
select reverse(
substring(
reverse(str_col)
, CHARINDEX(')', reverse(str_col))+1
, CHARINDEX('(', reverse(str_col))-2
)
)
from test;
如果 text/number 本身不包含 (
或 )
,这也应该有效
select replace(reverse(left(reverse(str_col), charindex('(', reverse(str_col)) -1)),')','')
from test;