2013-07-10 86 views
4

我有一个像SQL请求:测试一个字符串包含至少2个字在SQL

SELECT * 
FROM table 
WHERE lower(title) LIKE lower('%It's a beautiful string i think%') 

我需要检查,如果在我的字符串It's a beautiful string i think至少2个字包含在我的领域标题...我怎样才能做到这一点 ?

例如,如果在这个领域的头衔,我有串I think it's beautiful,该查询应该返回我这个对象...

谢谢!

+0

所以有行''我a''第二句得到单词的数量也应该被退回, 对? – dasblinkenlight

+1

你可以检查两个空间的存在:'LIKE( '_%_ %%')'。 – xbonez

+0

是为“我一个” ..或许检查前如果字含有较多的2个字符 –

回答

0

你可以动态生成下面的SQL语句:

SELECT title, count(*) 
FROM 
    (
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% It %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% s %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% a %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% beautiful %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% string %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% I %') 
    UNION ALL 
    SELECT title 
    FROM table1 
    WHERE (' ' + lower(title) + ' ') LIKE lower('% think %') 
    ) AS table2 
GROUP BY title 
HAVING COUNT(*) >= 2 

存储过程可能更有效,你可以对服务器端的整个工作完成。

0

你可以使用这样的函数

CREATE FUNCTION [dbo].[CheckSentece] (@mainSentence varchar(128), @checkSentence varchar(128)) 
RETURNS NUMERIC AS 
BEGIN 
    SET @mainSentence=LOWER(@mainSentence) 
    SET @checkSentence=LOWER(@checkSentence) 
    DECLARE @pos INT 
    DECLARE @word varchar(32) 
    DECLARE @count NUMERIC 
    SET @count=0 
    WHILE CHARINDEX(' ', @checkSentence) > 0 
    BEGIN 
    SELECT @pos = CHARINDEX(' ', @checkSentence) 
    SELECT @word = SUBSTRING(@checkSentence, 1, @pos-1)  
    DECLARE @LEN NUMERIC 

    //Simple containment check, better to use another charindex loop to check each word from @mainSentence 
    SET @LEN=(SELECT LEN(REPLACE(@mainSentence,@word,''))) 
    if (@LEN<LEN(@mainSentence)) SET @[email protected]+1  
    SELECT @checkSentence = SUBSTRING(@checkSentence, @pos+1, LEN(@checkSentence)[email protected]) 
    END 
    return @count 
END 

并从包含在第一个

相关问题