简体   繁体   English

提取字符串的两个部分

[英]Extracting two parts of a string

One of the fields in my results, contains the following "standard" notes: 结果中的字段之一包含以下“标准”注释:

Audit Status changed from STOP to RELEASED.
Audit Status changed from STOP to RFS Pend.
Audit Status changed from RELEASED to RFS Pend.
Audit Status changed from STOP to ODY Pend.
Audit Status changed from ODY Pend to RELEASED.

There may be other notes but these are the ones that I have seen so far. 可能还有其他注释,但这是我到目前为止所看到的。

What I would like to do is to extract 2 parts of each note with an expression. 我想做的是用一个表达式提取每个音符的2个部分。

The first part is the words between from and to ( STOP, RELEASED, ODY Pend, etc. ). 第一部分是from and to之间的单词( STOP, RELEASED, ODY Pend, etc. )。

The second part is the words after to ( RELEASED, RFS Pend, ODY, etc. ) 第二部分是“ to之后的单词( RELEASED, RFS Pend, ODY, etc.

I've tried split and it works but it makes the query run much longer (at least the way I tried to do for someone relatively new to sql). 我已经尝试了split并且它可以工作,但是它使查询的运行时间更长(至少我尝试为相对较新的sql尝试的方式)。 I've looked at using MID but I'm not sure how to write the expression since the starting point of each part is different. 我已经看过使用MID,但是由于每个部分的起点都不相同,因此我不确定如何编写表达式。

This should do it with MS SQL Server. 这应该使用MS SQL Server完成。

CREATE TABLE MyTable (col1 int IDENTITY(1,1), col2 varchar(50));

INSERT MyTable (col2) VALUES ('Audit Status changed from STOP to RELEASED.');
INSERT MyTable (col2) VALUES ('Audit Status changed from STOP to RFS Pend.');
INSERT MyTable (col2) VALUES ('Audit Status changed from RELEASED to RFS Pend.');
INSERT MyTable (col2) VALUES ('Audit Status changed from STOP to ODY Pend.');
INSERT MyTable (col2) VALUES ('Audit Status changed from ODY Pend to RELEASED.');

And... 和...

WITH MyData AS
(
  SELECT col1, 
    col2, 
    PATINDEX('% from %', col2) + 6 as Start1, 
    PATINDEX('% to %', col2) as Stop1,
    PATINDEX('%.', col2) as Stop2
  FROM MyTable
)
SELECT SUBSTRING(col2, Start1, Stop1-Start1) as Word1,
       SUBSTRING(col2, Stop1+4, Stop2-Stop1-4) as Word2
FROM MyData

I can't say that the performance will be any better than what you're doing now, but you can try it out and let us know. 我不能说性能会比您现在做的更好,但是您可以尝试一下并告诉我们。

NOTE: This will break down if the patterns (' from ', ' to ' or '.') occur more than once in your strings. 注意:如果模式(从','到'或'。')在您的字符串中出现多次,这将分解。 And you'll want to include some error handling or maybe a where clause to filter out values of zero (when the pattern is not found) that will result in negative lengths. 而且,您将希望包括一些错误处理,或者可能包括where子句,以过滤出零值(当未找到模式时),这将导致负长度。

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

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