简体   繁体   English

从 SQL 中的字符串中提取关键字

[英]Extracting Keywords from a string in SQL

I wanted to write a SQL query in SQL server that extracts certain keywords from a column holding string values.我想在 SQL 服务器中编写一个 SQL 查询,从包含字符串值的列中提取某些关键字。 The keywords are sitting in another Table -- (KEYWORDS).关键字位于另一个表中 - (KEYWORDS)。 Also in case, there are multiple keywords found in the same string, I want all the keywords found to be displayed.另外,如果在同一个字符串中找到多个关键字,我希望显示所有找到的关键字。

Egs鸡蛋

KEYWORDS -- Tom, Doctor, coach, value
TEXT -- Hi coach, tom here

Final O/p:最终 O/p:

**TEXT**                           
Hi coach, tom here  

**KEYWORDS_EXTRACTED**
coach, tom
declare @k table(thekeyword varchar(50));
insert into @k(thekeyword) values ('Tom'), ('Doctor') , ('coach'), ('value');

declare @t table(thetext varchar(1000));
insert into @t(thetext) values('Hi coach, tom here'), ('Tom visited the doctor'), ('minicoach or minibus?'), ('Tomas says hi')

select *
from @t as t
outer apply
(
    select
    stuff(
    (select ',' + k.thekeyword
        --string_agg(k.thekeyword, ',') as thekeywords
    from @k as k
    where ' ' + t.thetext + ' ' like '%[^A-Za-z]'+k.thekeyword+'[^A-Za-z]%' --adjust
    for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as thekeywords
) as kw;

You can use string_split() :您可以使用string_split()

select t.*, k.keyword
from t cross apply
     string_split(replace(text, ',', ' ')) s join
     keywords k
     on k.keyword = s.value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM