TSQL:如何通过复杂逻辑选择句子



你能帮我用复杂的逻辑选择一个句子吗?平台:TSQL .

初始数据:

0

如果您真的必须使用sql,只需在WHERE子句中使用多个条件。这样,您就不必调用函数来进行替换或其他操作。

你可以这样改写你的条件:

  • 文本中只包含Apple但不包含"Apple">
  • 文本同时包含Apple和"Apple">
    • 可能性1:首先是苹果,然后是"苹果">
    • 可能性2:先"apple",再"apple">
WHERE
(Col LIKE '%apple%' AND Col NOT LIKE '%"%apple%"%') -- APPLE, but not "APPLE"
OR Col LIKE '%apple%"%apple%"%'                     -- APPLE .. "APPLE" ..
OR Col LIKE '%"%apple%"%apple%'                     -- "APPLE" .. APPLE ..

,db&lt的在小提琴

您的示例数据和解释似乎只需要以下内容,这对您有用吗?

with d as (
select 'company "Apple corp" has an apple on its logotype  1' sentence union
select 'company "Apple computers" is a large company   0' union
select 'Apple company'
)
select * , case when Replace(Replace(sentence,'"apple',''),'apple"','') like '%apple%' then 1 else 0 end
from d;

我通过应用这个逻辑解决了这个问题。

  1. 用'|'代替Apple
  2. 从句子中删除除'|'和'"'以外的所有字符
  3. 用""代替""。处理一个引号同时属于两个单词"Apple"Apple">
  4. 的情况
  5. 从句子中删除所有带引号的字符'|'。
  6. 选择包含'|'的句子

首先,我们应该为点2创建函数。

create function [dbo].[fn_KeepCharacters](@String varchar(2000), @KeepValues varchar(255))
returns varchar(2000)
as
begin
set @KeepValues = '%['+@KeepValues+']%'
while patindex(@KeepValues, @String) > 0
set @String = stuff(@String, patindex(@KeepValues, @String), 1, '')
return @String
end
go

完整代码:

with d as (
select 'big company "Apple"' col 
union select 'Apple, start' 
union select 'comp Apple" computers'
union select  'inc " int Apple ap' 
union select '"i Apple""mac Apple" aa' 
union select 'book "pen Apple"pineApple"' 
union select 'leaf Apple"Apple"'
)
--, b as (
select col, case when replace(replace(dbo.fn_KeepCharacters(replace(col, 'Apple', '|'), '^"|'), '"', '""'), '"|"', '""') 
like '%|%' then 1 else null end
col_sec
from d

我感谢stackoverflow成员的帮助。特别是@Stu用于嵌套的替换通知。

问题,fn_KeepCharacters包含一个圆圈,这是非常慢的。如果有更快的解决方案,我将不胜感激。

最新更新