这里有两种方法,具体取决于您要做什么(假设FREETEXT
关键字中的 SQL 2005+)。示例数据之后的第一个选择返回关键字的索引(如果您不想要找不到的关键字,请过滤掉零)。第二个只是检查存在
Declare @keywords as table (keyword varchar(50))
INSERT INTO @keywords
VALUES ('quandary'),
('variable'),
('paragraph'),
('Narwhal')
DECLARE @input as varchar(max)
SET @input = 'Heres my quandary. I have a variable that contains a paragraph of text, and I have a column full of keywords. I want to search each of the keywords contained in the column against the entirety of the text contained within my variable'
SELECT keyword, CHARINDEX(keyword, @input , 0)
FROM @keywords
SELECT kw.keyword
FROM
(SELECT @input input) bigstring
INNER JOIN @keywords kw
on bigstring.input like '%' + kw.keyword + '%'
(4 row(s) affected)
keyword
----------------------- --------------------
quandary 10
variable 29
paragraph 54
Narwhal 0
(4 row(s) affected)
keyword
-----------------------
quandary
variable
paragraph
(3 row(s) affected)
如果也有 CROSS APPLY 解决方案,我不会感到惊讶
更新
仅获取第一个关键字作为输出参数
数据
CREATE TABLE table1 (keyword varchar(50))
INSERT INTO table1
VALUES ('quandary'),
('variable'),
('paragraph'),
('Narwhal')
GO
过程
CREATE proc testKeyword
@input varchar(1000),
@debug varchar(25) output
AS
BEGIN
SELECT TOP 1 @debug = kw.keyword
FROM (SELECT @input input) bigstring
INNER JOIN table1 kw
on bigstring.input LIKE '%' + kw.keyword + '%'
END
测试
DECLARE @debug varchar(25)
EXEC testKeyword 'Heres my quandary. I have a variable that contains a paragraph of text, and I have a column full of keywords. I want to search each of the keywords contained in the column against the entirety of the text contained within my variable',
@debug out
SELECT @debug
outputs
-------------------------
quandary
(1 row(s) affected)