SQL statement with multiple keywords in string in LIKE statement - sql

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%';
That works fine. What I am trying to achieve is to pass the keywords c("a", "_r", "si") as a vector. Like this:
keywords <- c("a", "_r", "si")
SELECT *
FROM Customers
WHERE CustomerName LIKE '%' + keywords + '%';
That did not work. How do I submit a variable with a bunch of keywords into the like statement?

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%'

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

create user defined WHERE SQL phrase in r

I am using RODBC to connect to a database. I would love for a user to be able to define wildcard strings to lookup in the SQL as part of a function. I cannot use CONTAINS as the database is not full-text indexed.
The SQL I want to create is
"SELECT *
FROM mydataTable
WHERE (ItemNM LIKE '%CT%' OR ItemNM LIKE '%MRI%' OR ItemNM LIKE '%US%')"
The user should be able to define as many wildcards as they like, all from the ItemNM field and all separated by OR.
myLookup<-function(userdefined){
paste0("SELECT *
FROM mydataTable
WHERE ( LIKE '",userdefined,"')")
}
If I vectorise the userdefined (ie userdefined<-c("US","MRI")) then I end up with separate SQL strings which is no good. How can I get the output as above but for any length of user defined string where they are just defining the wildcard?
You could use :
myLookup <- function(userdefined) {
paste0('SELECT * FROM mydataTable WHERE (',
paste0('ITENM LIKE %', userdefined, '%', collapse = " OR "), ')')
}
userdefined<-c("US","MRI")
myLookup(userdefined)
#[1] "SELECT * FROM mydataTable WHERE (ITENM LIKE %US% OR ITENM LIKE %MRI%)"
We can use glue
library(glue)
mylookup <- function(userdefined){
as.character(glue('SELECT * FROM mydataTable WHERE (',
glue_collapse(glue("ItemNM LIKE '%{userdefined}%'"), sep=" OR "), ')'))
}
mylookup(userdefined)
#[1] "SELECT * FROM mydataTable WHERE (ItemNM LIKE '%US%' OR ItemNM LIKE '%MRI%')"

Apply like function on an array is SQL Server

I am getting array from front end to perform filters according that inside the SQL query.
I want to apply a LIKE filter on the array. How to add an array inside LIKE function?
I am using Angular with Html as front end and Node as back end.
Array being passed in from the front end:
[ "Sports", "Life", "Relationship", ...]
SQL query is :
SELECT *
FROM Skills
WHERE Description LIKE ('%Sports%')
SELECT *
FROM Skills
WHERE Description LIKE ('%Life%')
SELECT *
FROM Skills
WHERE Description LIKE ('%Relationship%')
But I am getting an array from the front end - how to create a query for this?
In SQL Server 2017 you can use OPENJSON to consume the JSON string as-is:
SELECT *
FROM skills
WHERE EXISTS (
SELECT 1
FROM OPENJSON('["Sports", "Life", "Relationship"]', '$') AS j
WHERE skills.description LIKE '%' + j.value + '%'
)
Demo on db<>fiddle
As an example, for SQL Server 2016+ and STRING_SPLIT():
DECLARE #Str NVARCHAR(100) = N'mast;mode'
SELECT name FROM sys.databases sd
INNER JOIN STRING_SPLIT(#Str, N';') val ON sd.name LIKE N'%' + val.value + N'%'
-- returns:
name
------
master
model
Worth to mention that input data to be strictly controlled, since such way can lead to SQL Injection attack
As the alternative and more safer and simpler approach: SQL can be generated on an app side this way:
Select * from Skills
WHERE (
Description Like '%Sports%'
OR Description Like '%Life%'
OR Description Like '%Life%'
)
A simple map()-call on the words array will allow you to generate the corresponding queries, which you can then execute (with or without joining them first into a single string).
Demo:
var words = ["Sports", "Life", "Relationship"];
var template = "Select * From Skills Where Description Like ('%{0}%')";
var queries = words.map(word => template.replace('{0}', word));
var combinedQuery = queries.join("\r\n");
console.log(queries);
console.log(combinedQuery);

Like statement across multiple columns in SQL

I'm trying to query a like statement across multiple columns. I have the following search terms:
'dog'
'cat'
'rabbit'
'gerbil'
'guinea pig'
'hamster'
and I need search for these terms or terms LIKE these in the 'animals' table which has about 40 different columns. I am aware I can do the like statement by doing
Select * from animals where [animalscolumn] like ('%dog%') or like ('%cat%') or like ('%gerbil%') or like ('%hamster%') or like ('%guinea pig%')
However the 'animalscolumn' isn't the only column I need to run the 'LIKE' statement across. I have to search for these terms in about 40 columns. Would anyone happen to know how? Thanks!
multiple like statements can not be used with or directly. You have to use column name for each like statement.
Use multiple like as mentioned below.
Select *
from animals
where
(
[animalscolumn] like ('%dog%') or
[animalscolumn] like ('%cat%') or
[animalscolumn] like ('%gerbil%') or
[animalscolumn] like ('%hamster%') or
[animalscolumn] like ('%guinea pig%')
)
If you want to find a set of number you can use IN
SELECT *
FROM tableName
WHERE columnId IN (154,156,133,157,119)
$sql = "SELECT * from like1 WHERE tutorial_author LIKE '$apply'
OR
tutorial_title LIKE '$apply'";
if($mode == 'search_contact'){
// $prefix='%';
$apply=$dataObj['search'];
$data = array();
// $sql = "SELECT * from add_contact WHERE tutorial_author OR tutorial_title LIKE '$apply'";
$sql = "SELECT * from add_contact WHERE
first_name LIKE '%$apply%'
OR
last_name LIKE '%$apply%'
OR
title LIKE '%$apply%'
OR
company LIKE '%$apply%'
OR
address LIKE '%$apply%'";
$result = $myConnection->query($sql);
if ($result->num_rows > 0) {
// print_r($result->fetch_assoc());
while($row = $result->fetch_assoc()) {
$row['user_image'] = site_url.upload_dir.$row['image'];
// print_r($row);
$data[]=$row;
}
$array = array('status'=>true, 'message'=> 'contacts fetched successfully', 'data'=> $data);
echo json_encode($array);
exit;
} else {
$array = array('status'=>false, 'message'=> "No contacts available" );
echo json_encode($array);
exit;
}
}
Select * from cscart_users
where status like '%a' and user_type like '%c' and firstname like '%az%';
Select * from cscart_users where status like '%a' and user_type like '%c'and firstname like'%az%';
syntax:
select * from tablename where columnname like'%b' and columnname2 like '%g';
Here is an example of a SQL Server stored procedure that takes a parameter.
CREATE PROCEDURE [dbo].sp_SearchMultiple #SearchTerm nvarchar(256)
AS
BEGIN
SET #SearchTerm = '%' + #SearchTerm + '%'
SELECT TOP 100
id, col1, col2, col3
FROM
asset_f
WHERE
col1 LIKE #SearchTerm OR col2 LIKE #SearchTerm OR col3 LIKE #SearchTerm
ORDER BY
id ASC
END

Querying a LinqToSql result

Let's say I have a Persons table with two columns:
ID (Uniqueidentifier)
Name (NChar)
I need to get all my persons first:
Dim data = (From p In Persons Select p).ToList
Now that I got all persons in the data variable, is it possible to query this result using a string query? Like...
Dim filtered = (From p In data Select p).Where("Name Like '%John%').ToList
?
I need to build the query on the fly.
Thanks
var filtered = data.Where(a =>
SqlMethods.Like(a.name.ToString(), "%" +
Request.QueryString["search"] + "%"));
i use querystring as an example for dynamic value, and use it in sql like method,
which is similiar to sql like, in your case "request.querystring["search"] value is john"
Try this:
from p in data
where SqlMethods.Like(p.Name, "%"+parameter+"%")
select p;
parameter in your example should be John.

use a regex capture in a pgSQL select

I've never used a regex in SQL. If I capture something like this in javascript, how can I refer back to the capture in pgSQL like I can with the 2nd element in javascript match() method?
var str = 'thomas-var1="SOME VAL1" thomas=var2="SOME VAL2" thomas-var-3="the value i want" thomas-var-4="SOME_VAL4"';
var re = /thomas-var-3="(.+?)"/i;
var new_str = str.match(re);
console.log(new_str[1]);
How can I put that into a SELECT statement so that I can say something like, retrieving the value "the value i want" from thomas-var-3?
SELECT * FROM forms WHERE name LIKE '%bill%' AND category = MY REGEX CAPTURE
rendering so something like"
SELECT * FROM forms WHERE name LIKE '%bill%' AND category ='the value i want'
you can use not regex, but hstore extension for this, like:
str := 'thomas-var1="SOME VAL1" thomas-var2="SOME VAL2" thomas-var-3="the value i want"'
str := replace(replace(str, '=', '=>'), '" ', '", ')
select *
from forms
where name like '%bill%' and category = hstore(str)->'thomas-var-3'
Using a subselect and the substring method you should be able to achieve what you want like so:
SELECT *
FROM firstTable
WHERE parentCat = (SELECT cat
FROM secondTable
WHERE cat in substring(column_to_capture_from from 'thomas-var-3="(.+?)' ));
from http://www.regular-expressions.info/postgresql.html
If there is a match, and the regex has one or more capturing groups, the text matched by the first capturing group is returned.