如何在 contains 函数的参数中使用 table 的字段?

how to use a field of a table in the parameter of the contains function?

我正在尝试使用 table 的字段作为 contains 方法的参数,但我不知道该怎么做。

我正在尝试这个:

SELECT * FROM tableA AS t1 WITH(UPDLOCK), TableB AS t2
 WHERE CONTAINS(t1.FieldX, '"' + t2.FieldY + '"')
   AND t2.ID IN(1,2,3,4,5);

但是我收到一条错误消息,提示在第一个“+”之前应该有一个“)”。

我该怎么做?

您要查找的函数是 CHARINDEX 或 PATINDEX...

where CHARINDEX('"' + t2.FieldY + '"', t1.FieldX) <> 0

不确定您是否需要 '"' 如果要使用通配符,请使用 PATINDEX 函数 让我知道这个是否奏效。

你可以不用 containsfull-text-search,我的意思是使用 like[=16] =] 运算符:

select * from tableA as t1 with(UPDLOCK), TableB as t2
where t1.FieldX like '%"'+t2.FieldY+'"%'
and t2.ID IN(1,2,3,4,5);

您不能在使用 SQL 服务器全文的一次查询中执行此操作。您实际上是在尝试 运行 对每一行进行不同的全文查询。

您实际上必须 运行 为每一行单独查询,如下所示:

-- put all tableA.ID values in table var so we can loop through them
declare @tableARowsToSearch table (ID int)
INSERT @tableARowsToSearch
SELECT ID FROM tableA WITH(UPDLOCK)

declare @fullTextResults table (ID int, FieldX varchar(max), ...)

-- for each tableA.ID...
declare @currentID int, @fullTextCondition nvarchar(4000)
set @currentID = (SELECT TOP 1 ID FROM @tableARowsToSearch ORDER BY ID)
while (@currentID is not null) begin
    -- construct full text condition based on TableB.FieldY
    set @fullTextCondition = (
        SELECT t2.FieldY FROM tableA AS t1 WITH(UPDLOCK), TableB AS t2
         WHERE t1.ID = @currentID
           AND t2.ID IN(1,2,3,4,5)
    )

    -- run full text query against one row in tableA
    INSERT @fullTextResults
    SELECT t1.ID, t1.FieldX, ... FROM tableA AS t1 WITH(UPDLOCK)
     WHERE t1.ID = @currentID
       AND CONTAINS(t1.FieldX, @fullTextCondition)

    set @currentID = (SELECT TOP 1 ID FROM @tableARowsToSearch WHERE ID > @currentID ORDER BY ID)
end

这可能会很慢。您最好使用 LIKE(参见 Tan_Blaytan 的回答)或考虑重新设计您的表格。