我正在尝试使用表的字段作为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);
然而,我收到一条错误消息,指出这是预期的")"在第一个" +"。
之前我该怎么做?
答案 0 :(得分:1)
您正在寻找的功能是CHARINDEX或PATINDEX ......
CHARINDEX('"' + t2.FieldY +'"',t1.FieldX)<> 0
不确定您是否需要'"' 如果要使用通配符,请使用PATINDEX函数 让我知道这个是否奏效。
答案 1 :(得分:1)
你可以在没有包含和全文搜索的情况下完成,我的意思是使用之类的运算符:
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);
答案 2 :(得分:0)
您无法在一个带有SQL Server全文的查询中执行此操作。您实际上是在尝试针对每一行运行不同的全文查询。
您必须为每一行实际运行单独的查询,如下所示:
-- 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的回答)或考虑重新设计你的桌子。