我有一个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 :(得分:2)
您可以将字符串拆分为临时表(例如,使用类似这样的内容:http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/),然后使用计数进行连接。
答案 1 :(得分: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
存储过程可能更有效,您可以在服务器端完成整个工作。
答案 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 @count=@count+1
SELECT @checkSentence = SUBSTRING(@checkSentence, @pos+1, LEN(@checkSentence)-@pos)
END
return @count
END
并获取第一句中包含的第二句话中的单词数