【问题标题】:How to find records searched in all columns of table with multiple keyword in SQL Server?如何在SQL Server中查找在具有多个关键字的表的所有列中搜索的记录?
【发布时间】:2017-03-30 20:55:30
【问题描述】:

我想用空格分隔的任何关键字搜索所有字段中的数据

举例

表名:SampleTable

col1    |  col2  |   col3    |   col4 |  col5
-----------------------------------------------
my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null
Name    |  will  | Describe  |  a     | person

如果用户按“”字词搜索 select * from SampleTable where allColumn=is 它必须将结果带入前两行

my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null

如果按is name 搜索。它必须带第一行

my      |  name  |    is     | john   | Abraham

如果按Abraham is 搜索。它必须带第一行和第二行

my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null

它几乎就像搜索引擎。你有什么想法吗?

【问题讨论】:

  • 所以搜索是区分大小写的吧?由于搜索“名称”排除了“名称”
  • @mastarhian 不区分大小写。
  • 原谅我..是“名字”
  • @mastarhian "is" & "name" 是 2 个单词,这两个单词只出现在一行中。所以我需要那一行
  • 至少可以说这是一个非常奇怪的要求。您将需要使用字符串拆分器将用户输入分成单词,然后在任何匹配的列上加入您的表,并计算发送的单词数和特定行匹配的次数。如果有人搜索“姓名”怎么办??

标签: sql sql-server database stored-procedures


【解决方案1】:

您似乎想要全文搜索。我建议您从documentation 开始。

如果你真的想使用like并且你想按照你的方式传递的话,那么我建议拆分字符串:

with terms as (
      select cast(left(@search, charindex(' ', @search + ' ') - 1) as varchar(max)) as term,
             cast(stuff(@search, 1, charindex(' ', @search + ' ') + 1, '') as varchar(max)) as rest
      union all
      select cast(left(rest, charindex(' ', rest + ' ') - 1) as varchar(max)),
             cast(stuff(rest, 1, charindex(' ', rest + ' ') + 1, '') as varchar(max))
      from terms
      where term <> ''
    )
select s.*
from sampleTable s cross apply
     (select count(*) as numterms,
             sum(case when t.term in (col1, col2, col3, col4, col5) then 1 else 0 end) as nummatches
      from terms t
     ) tt
where tt.numterms = tt.nummatches ;

【讨论】:

  • 即使不是最好的,他也是最好的之一。
  • @GordonLinoff 最后一行t.nummatches 显示错误
  • @gordonlinoff 我更改为ttnummatches 然后当我执行时,此错误显示Types don't match between the anchor and the recursive part in column "term" of recursive query "terms".
  • @mohamedfaiz 。 . .我不知道为什么 SQL Server 对递归 CTE 中的字符串数据类型如此挑剔。投射到一个共同的长度可以解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-04-26
  • 2018-07-03
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多