简体   繁体   English

在字符串的一部分中搜索模式

[英]Search for pattern in part of the string

I need to search for a pattern in a string field which contains an email and an additional comment. 我需要在包含电子邮件和其他注释的字符串字段中搜索模式。 An example is the following: 下面是一个示例:

Dear XXX: We are sorry to inform you that your 
application has been put on hold because YYY. 

Additional comments: this application was not held for ZZZ.

The pattern I am looking for is "ZZZ" in the email body. 我正在寻找的模式是电子邮件正文中的“ ZZZ”。 But not in the comments. 但不在评论中。 If I just do field like 'ZZZ' , I will be picking up this record, which is not what I want. 如果我只是field like 'ZZZ'这样的field like 'ZZZ' ,我将拿起这个记录,这不是我想要的。 Is there a way to carry out the search accurately in this case? 在这种情况下,有没有一种方法可以准确地执行搜索?

Note that a subset of the records have the field structured this way, others may not contain this structure (ie no Additional comments: . The bold letters mark the structure of the subset. 请注意,记录的子集具有以这种方式构造的字段,其他子集可能不包含此结构(即,没有Additional comments: 。粗体字母标记该子集的结构。

如果总会有“其他注释:”,则可以执行以下操作:

WHERE field LIKE '%ZZZ%' AND field NOT LIKE 'Additional comments:%ZZZ%'

Give this a try: 试试看:

WITH cte
AS
    (SELECT
        CASE
            WHEN CHARINDEX('Additional Comment',[field]) = 0 THEN [field]
            WHEN CHARINDEX('Additional Comment',[field]) > 0 THEN 
                LEFT([field],CHARINDEX('Additional Comment',[field])-1)
        END AS Adjusted_field
    FROM table)

SELECT Adjusted_field
FROM cte
WHERE
    Adjusted_field LIKE '%zzz%'

This uses a CTE to basically remove anything after the "Additional Comment" line in the text field. 这使用CTE基本上删除了文本字段中“其他注释”行之后的所有内容。 The CASE statement uses CHARINDEX to search for the "Additional Comment" if that string is not found (CHARINDEX =0) then it returns the whole text field, if the string is found then it only returns the text that came before (LEFT) of the "additional comment" string. 如果找不到该字符串(CHARINDEX = 0),则CASE语句使用CHARINDEX搜索“其他注释”,然后返回整个文本字段,如果找到该字符串,则仅返回(LEFT)之前的文本。 “其他注释”字符串。

Then in the final SELECT query you can search for the desired string in the adjusted text field which now entirely ignores anything that came after the "additional comment" string. 然后,在最终的SELECT查询中,您可以在调整后的文本字段中搜索所需的字符串,现在该字段将完全忽略“附加注释”字符串之后的所有内容。

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

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