Home > database >  SQL statement with multiple keywords in LIKE statement
SQL statement with multiple keywords in LIKE statement

Time:11-11

I am trying to pull data based on multiple keywords from the same column.

Currently I have a SQL statement that works like this.

SELECT * 
FROM Customers
WHERE CustomerName LIKE 'a%'
   OR CustomerName LIKE '_r%'
   OR CustomerName LIKE 'si%';

This works fine. What I am trying to achieve is pass the keywords c("a", "_r", "si") as a vector. Something like this.

keywords <- c("a", "_r", "si")

SELECT * 
FROM Customers
WHERE CustomerName LIKE '%'   keywords   '%';

I tried this above and it did not work, so please advise on how to submit a variable with bunch of keywords into the like statement.

Thanks

CodePudding user response:

Use sprintf and paste/collapse= . Within a sprintf format %s is replaced with the next argument and %% means %.

keywords <- c("a", "_r", "si")

sql <- keywords |>
  sprintf(fmt = "CustomerName LIKE '%%%s%%'") |>
  paste(collapse = " OR \n") |>
  sprintf(fmt = "SELECT *
    FROM Customers
    WHERE %s")

cat(sql, "\n")

giving:

SELECT *
    FROM Customers
    WHERE CustomerName LIKE '%a%' OR 
CustomerName LIKE '%_r%' OR 
CustomerName LIKE '%si%' 

CodePudding user response:

Just another option using string_split() and a JOIN

Example

DECLARE @Find VARCHAR(max) = ('a%,_r%,si%')

Select Distinct A.* 
 From Customers A
 Join string_split(@Find,',') B
   on CustomerName like B.value
  • Related