选择具有缺少某个前缀的子字符串的行

时间:2018-02-09 06:34:01

标签: sql-server tsql

我有一个带有nvarchar列的表。我想选择该列包含某个单词的行,但前提是它前面没有另一个单词。示例数据:

DECLARE @T AS TABLE
(
    Phrase nvarchar(50)
)

INSERT INTO @T VALUES (N'Jeffie likes big cookies.'),
    (N'Good cookies can be made with chocolate.'),
    (N'Maggie likes big cookies and little cookies.')

如果“cookies”之前没有“cookies”,则查询应返回“cookies”出现的行。对于上述数据,查询应返回第一行和第三行。第三行是问题所在,因为'cookies'出现两次,之前只有'big'一次。我得到的最接近的是以下查询,但它不太正确:

SELECT * FROM @T 
WHERE Phrase LIKE N'%cookies%'
AND Phrase NOT LIKE N'%big cookies%'

此查询的问题是它只返回第一行,我希望它返回第一行和第三行。提前感谢任何建议!

3 个答案:

答案 0 :(得分:2)

尝试这种方法

DECLARE @T AS TABLE
(
    Phrase nvarchar(50)
)

INSERT INTO @T VALUES 
(N'Jeffie likes big cookies.'),
(N'Good cookies can be made with chocolate.'),
(N'Maggie likes big cookies and little cookies.')


SELECT 
    *
    FROM @T
       WHERE (LEN(Phrase)-LEN(REPLACE(Phrase,'Big Cookies','')))/LEN('Big Cookies') 
       <> (LEN(Phrase)-LEN(REPLACE(Phrase,'cookies','')))/LEN('cookies')

我的结果

enter image description here

答案 1 :(得分:1)

请尝试这个简单的解决方案 -

DECLARE @T AS TABLE ( Phrase nvarchar(50) )

INSERT INTO @T VALUES 
  (N'Jeffie likes big cookies.')
, (N'Good cookies can be made with chocolate.')
, (N'Maggie likes big cookies and little cookies.'),
(N'big I am here cookies and little cookies.'),
(N'anything here'),
(N'Maggie likes big cakes and little cookies'),
(N'big cookies big cookies')

SELECT * FROM @T where CHARINDEX ('cookies' , REPLACE(Phrase,'big cookies','xxx'))  >0 

输出

Phrase
--------------------------------------------------
Good cookies can be made with chocolate.
Maggie likes big cookies and little cookies.
big I am here cookies and little cookies.
Maggie likes big cakes and little cookies

(4 rows affected)

答案 2 :(得分:0)

试试这个:

SELECT * FROM @T 
WHERE Phrase LIKE N'%big cookies%'
AND charindex('cookies',Phrase) > 0

WHERE子句的执行顺序将使用&#39;大cookie检查第一个条件&#39;然后它会因为AND而解决目的。