4

我有一个 sql 请求,例如:

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

我需要检查我的字符串中是否至少有 2 个单词It's a beautiful string i think包含在我的字段标题中......我该怎么做?

例如,如果在我的字段标题中我有字符串I think it's beautiful,这个查询应该返回我这个对象......

谢谢 !

4

3 回答 3

2

您可以将您的字符串拆分为一个临时表(例如,使用类似这样的内容:http: //ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/)然后进行连接,计数。

于 2013-07-10T09:20:58.507 回答
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 @count=@count+1     
    SELECT @checkSentence = SUBSTRING(@checkSentence, @pos+1, LEN(@checkSentence)-@pos)
  END
  return @count
END

并从第一个句子中包含的第二个句子中获取单词数

于 2013-07-10T09:41:02.623 回答
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

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

于 2013-07-10T09:36:40.687 回答