简体   繁体   中英

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. The keywords are sitting in another Table -- (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:

**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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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