Orin Moyer
Orin Moyer

Reputation: 509

SQL Search rows that contain strings from 2nd table list

I have a master table that contains a list of strings to search for. it returns TRUE/FALSE if any string in the cell contains text from the master lookup table. Currently I use excel's

=SUMPRODUCT(--ISNUMBER(SEARCH(masterTable,[@searchString])))>0

is there a way to do something like this in SQL? LEFT JOIN or OUTER APPLY would be simple solutions if the strings were equal; but they need be contains..

SELECT *
FROM t
WHERE col1 contains(lookupString,lookupColumn)


--that 2nd table could be maintained and referenced from multiple queries
hop
bell
PRS
2017

My desired results would be a column that shows TRUE/FALSE if the row contains any string from the lookup table

 SEARCH_STRING      Contained_in_lookup_column
 hopping                 TRUE
 root                    FALSE
 Job2017                 TRUE
 PRS_tool                TRUE
 hand                    FALSE

Upvotes: 1

Views: 610

Answers (2)

Sergio.Gaspar
Sergio.Gaspar

Reputation: 66

Sorry i dont have access to the DB now to confirm the syntax, but should be something like this:

SELECT t.name,
case when (select count(1) from data_table where data_col like '%' || t.name || '%' > 0) then 'TRUE' else 'FALSE' end
FROM t;

or

SELECT t.name,
case when exists(select null from data_table where data_col like '%' || t.name || '%') then 'TRUE' else 'FALSE' end
FROM t; 

Sérgio

Upvotes: 1

Frank Schmitt
Frank Schmitt

Reputation: 30765

You can use a combination of % wildcards with LIKE and EXISTS.

Example (using Oracle syntax) - we have a v_data table containing the data and a v_queries table containing the query terms:

with v_data (pk, value) as (
  select 1, 'The quick brown fox jumps over the lazy dog' from dual union all
  select 2, 'Yabba dabba doo' from dual union all
  select 3, 'forty-two' from dual
),
v_queries (text) as (
  select 'quick' from dual union all
  select 'forty' from dual
)
select * from v_data d
where exists (
  select null 
  from v_queries q
  where d.value like '%' || q.text || '%');

Upvotes: 0

Related Questions