简体   繁体   English

SQL正则表达式查询以匹配单词的完全匹配

[英]Sql regex query to match exact matches of the word

My query is 我的查询是

DECLARE @Values TABLE
(
  value NVARCHAR(255)
)

INSERT INTO @Values VALUES('BWE');
INSERT INTO @Values VALUES('BWT');
INSERT INTO @Values VALUES('IMO I');
INSERT INTO @Values VALUES('IMO II');
INSERT INTO @Values VALUES('BWE-E');
INSERT INTO @Values VALUES('BWE-EP');
INSERT INTO @Values VALUES('IMO III');
INSERT INTO @Values VALUES('BWM-EP(s)');
INSERT INTO @Values VALUES('BWM-EP');

select * from @Values


SELECT  a.value
      FROM @Values a
      INNER JOIN (SELECT 'BWM-EP(s)' AS CLASS_NOTATION) b 
      ON     LTRIM(RTRIM(b.CLASS_NOTATION)) like '%[^a-z0-9]' + LTRIM(RTRIM(a.VALUE)) + '[^a-z0-9]%'
            or LTRIM(RTRIM(b.CLASS_NOTATION)) like LTRIM(RTRIM(a.VALUE)) + '[^a-z0-9]%'
            or LTRIM(RTRIM(b.CLASS_NOTATION)) like '%[^a-z0-9]' + LTRIM(RTRIM(a.VALUE)) 
            or LTRIM(RTRIM(b.CLASS_NOTATION)) = LTRIM(RTRIM(a.VALUE)) 

It works in most of the cases of class notation . 它适用于大多数的类表示法。 but in this particular case when I have 'BWM-EP(s)' as class notation it gives you both BWM-EP(s) and BWM-EP . 但是在这种特殊情况下,当我使用“ BWM-EP”作为类符号时,它会同时为您提供BWM-EP和BWM-EP。 But result should be only BWM-EP(s) . 但是结果应该只是BWM-EP。 What is wrong ? 怎么了 ?

As I see from the answers even though the root cause for this problem is second OR condition . 从答案中可以看出,即使此问题的根本原因是第二个OR条件。 I cannot exclude that condition as i need that when the class notation is BWE BWT . 我不能排除该条件,因为当类标记为BWE BWT时,我需要这样做。 How can i overcome from this ? 我该如何克服呢?

It's the 这是

or LTRIM(RTRIM(b.CLASS_NOTATION)) like LTRIM(RTRIM(a.VALUE)) + '[^a-z0-9]%'

condition that matches the BWM-EP value. BWM-EP值匹配的条件。

This makes sense; 这很有道理; this expression can be reduced to 'BMW-EP(s)' like 'BMW-EP'[^a-z0-9]% for the BMW-EP record, which is obviously true. 对于BMW-EP记录,此表达式可以减少为'BMW-EP(s)' like 'BMW-EP'[^a-z0-9]% ,这显然是正确的。

Here's how it works without that: http://www.sqlfiddle.com/#!3/e5251/6 没有它的工作原理如下: http : //www.sqlfiddle.com/#!3/e5251/6

Try this one - 试试这个-

DECLARE @Values TABLE (value NVARCHAR(255))
INSERT INTO @Values
VALUES 
    ('BWE'),('BWT'),('IMO I'),('IMO II'),
    ('BWE-E'),('BWE-EP'),('IMO III'),
    ('BWM-EP(s)'),('BWM-EP')

SELECT value
FROM (
    SELECT value = LTRIM(RTRIM(value))
    FROM @Values
) a
CROSS JOIN (
    SELECT note = LTRIM(RTRIM('BWM-EP(s)'))
) t
where note LIKE '%[^a-z0-9]' + value + '[^a-z0-9]%'
    OR note LIKE '%[^a-z0-9]' + value
    OR note = value

Output - 输出-

value
----------
BWM-EP(s)

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

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