如何在包含查询中动态编写 OR 子句?

How to dynamically write OR clause in Contains query?

有没有办法从字符串拆分中生成此 SQL 查询的第二部分(OR 子句)?

WHERE CONTAINS(t.something, '"bla*" OR "foo*" OR "batz*"')

字符串拆分值来自:

DECLARE @String_With_Commas varchar(max);
SET @String_With_Commas = 'Mercedes, BMW, Audi, Tesla, Land Rover';

select value from string_split(@String_With_Commas,',')

您可以使用 STRING_SPLIT() 拆分字符串,然后使用 STRING_AGG() 重建它,并将结果字符串简单地传递到 CONTAINS:

DECLARE @String_With_Commas nvarchar(255);
SET @String_With_Commas = N'Mercedes, BMW, Audi, Tesla, Land Rover';

DECLARE @SearchPhrase nvarchar(max);

SELECT @SearchPhrase = CONCAT(N'"', 
  STRING_AGG(LTRIM(value), N'*" OR "'), N'*"')
  FROM STRING_SPLIT(@String_With_Commas, N',') AS s;

SELECT ...
WHERE CONTAINS(t.something, @SearchPhrase);

或者更简单:

DECLARE @String_With_Commas nvarchar(255);
SET @String_With_Commas = N'Mercedes, BMW, Audi, Tesla, Land Rover';

DECLARE @SearchPhrase nvarchar(max)
 = CONCAT(N'"', REPLACE(@String_With_Commas, N', ', N'*" OR "'), '*"');

SELECT ...
WHERE CONTAINS(t.something, @SearchPhrase);

在这两种情况下,@SearchPhrase 看起来像这样:

"Mercedes*" OR "BMW*" OR "Audi*" OR "Tesla*" OR "Land Rover*"