繁体   English   中英

如何使用内置函数从字符串的随机位置提取子字符串?

[英]How do I extract a substring from a random position in a string using built-in functions?

我以以下方式存储了一系列数据:

Word of various kinds (ANT\username1) and even more words
This is another row, the words are random (ANT\username2)
Thankfully the username only ever shows once (ANT\username1)

上方代表三个独立的行。

该数据的一般流程为:

  • 括号可以出现在文本中的任何位置
  • 每个字符串的用户名部分(ANT \\ usernamex)只会出现一次
  • 用户名部分前后的文本长度始终不同。
  • 用户名文本可能并不总是存在

正如您可能已经猜到的,我需要做的是从每一行中获取用户名,如果用户名不存在,则返回null。 不幸的是,我不知道该如何处理-我玩过left()和right()函数,但实际上不知道该如何解决。 如果使用了许多功能来完成任务的答案有一个简短的讲解,以解释逻辑流程,将不胜感激(因此,我可以阅读文档以学习这些功能)。

当数据不符合预期时,请注意特定结果。 这完全适用于格式'(ANT\\....)'

-- sample table
create table t(s varchar(max));
insert t select 
'Word of various kinds (ANT\) blank' union all select
'Word of various kinds (ANT) blank' union all select
'Word of various kinds (ANT\ no closing' union all select
'Word of various kinds (ANT\(ANT\me) double up' union all select
'' union all select
'(ANT\' union all select
null union all select
'Word of various kinds (ANT\username1) and even more words' union all select
'This is another row, the words are random (ANT\username2)' union all select
'Thankfully the username only ever shows once (ANT\username1)';

-- Query
select Original = s,
       Extracted = nullif(STUFF(LEFT(s, CharIndex(')',s+')',
                   PatIndex('%(ANT\%', s)) -1), 1,
                   PatIndex('%(ANT\%', s + '(ANT\')+4,''),'')
from t;

暂无
暂无

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

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