2013-07-10 83 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 

並從包含在第一個

相關問題