a sql query with multiple search word - sql

i use following query to get all data which contains the some words (which is split by a function) in the name column of the inventoryLocalization table.
in the example i have split "red green blue" string.
as it should be, it returned all rows like OR operator.
SELECT distinct
inL.name
FROM dbo.[inventoryLocalization] inL
JOIN fnSplitString (N'red green blue',' ' ) words ON (inL.name LIKE '%'+ words.item +'%')
My question is, is it possible to get rows which has all words, as in the AND operator.

select inL.name from dbo.[inventoryLocalization] inL
where not exists
(select 1 from fnSplitString(N'red green blue',' ') words
where (inL.name NOT LIKE '%'+ words.item +'%'))

Try something like this:
DECLARE #SomeWords NVARCHAR(200), #Num INT
SET #SomeWords = 'red green blue'
SELECT #Num = COUNT(*)
FROM fnSplitString (#SomeWords,' ')
SELECT inL.name
FROM dbo.[inventoryLocalization] inL
JOIN fnSplitString (#SomeWords,' ' )words
ON (inL.name LIKE '%'+ words.item +'%')
GROUP BY inL.name
HAVING COUNT(*) = #Num

Related

SQL Query Dynamically Create Multiple LIKE/OR Clause

I am trying to create the answer
SELECT *
FROM table
WHERE column LIKE 'Text%'
OR column LIKE 'Hello%'
OR column LIKE 'That%'
in below link:
Combining "LIKE" and "IN" for SQL Server
The problem is, in my example the values in the answer 'Text', 'Hello' and 'That' are not hard coded, they are populated from an application multi-select control and can be NULL value or a comma-separated string like this :
DECLARE #String_With_Commas nvarchar(255);
SET #String_With_Commas = N'Mercedes,BMW,Audi,Tesla,Land Rover';
I have tried below code, but it didn't work :
DECLARE #SearchString = CONCAT('''',REPLACE(#String_With_Commas, N',', N'%'' OR column LIKE '''));
And use it like :
WHERE column LIKE #SearchString + '%' + ''''
Assuming you are using a fully supported version of SQL Server, a couple ideas:
JOIN to STRING_SPLIT:
SELECT *
FROM dbo.YourTable YT
JOIN STRING_SPLIT(#YourVariable,',') SS ON YT.YourColumn LIKE SS.[value] + '%';
This will, however, return multiple rows if there can be multiple matches.
Use an EXISTS:
SELECT *
FROM dbo.YourTable YT
WHERE EXISTS (SELECT 1
FROM STRING_SPLIT(#YourVariable,',') SS
WHERE YT.YourColumn LIKE SS.[value] + '%');
This won't return the same row twice, if there are multiple matches.
From the comments on this answer, the requirement that the parameter be NULLable was omitted in the question. I would therefore suggest you use the EXISTS solution:
SELECT *
FROM dbo.YourTable YT
WHERE EXISTS (SELECT 1
FROM STRING_SPLIT(#YourVariable,',') SS
WHERE YT.YourColumn LIKE SS.[value] + '%')
OR #YourVariable IS NULL
OPTION (RECOMPILE);

SQL how to do a LIKE search on each value of a declared variable

I have a query where I am trying to do a LIKE search on each value of a declared variable, instead of doing a like search on the entire field value/string.
Example:
DECLARE #name VARCHAR(30)
SET #name = 'John Smith'
SELECT name FROM customers WHERE name like '%'+ #name + '%'
The record I am looking for is "John and Jane Smith". The query above returns NO result. If the user searches just 'John' OR just 'Smith' there are too many results returned.
I am trying to get the query to search like the query below:
SELECT name from customers WHERE name LIKE '%John% %Smith%'
I've searched for many options but not sure if my search terms are not correct, I have yet to find a solution.
I would try replacing spaces in your #name with '% %'
Something like
SET #nameFilter = REPLACE(#name,' ','% %')
SELECT name FROM customers WHERE name like '%'+ # nameFilter + '%'
A full-text search seems like the best approach. But you can approximate this at the word level by splitting the search term and looking for each individual word:
with words as (
select value as word
from string_split(#name)
)
select c.name
from customers c cross apply
(select count(*) as cnt
from words w
where c.name like '%' + c.word + '%'
) w
where w.cnt = (select count(*) from words);
This uses the string_split() functionality available in more recent versions of SQL Server. There are online versions of the function for older versions.
This was answered/accepted before I could post and what #sugar2Code posted is how I would do it.
That said, I was unclear if you wanted both the first and last name needed to be similar or just one of them. What I put together will allow you to decide using a parameter.
-- Sample Data
DECLARE #t TABLE (CustomerName VARCHAR(30))
INSERT #t VALUES('Johny Smith'),('Freddie Roach'),('Mr. Smithers'),('Johnathan Smithe');
-- User Arguments
DECLARE
#name VARCHAR(30) = 'John Smith',
#partialmatch BIT = 1;
-- Dynamic Solution
SELECT
t.CustomerName,
FNMatch = SIGN(pos.F),
LNMatch = SIGN(pos.L)
FROM #t AS t
CROSS JOIN
(
SELECT SUBSTRING(#name,1,f.Mid-1), SUBSTRING(#name,f.Mid+1,8000)
FROM (VALUES(CHARINDEX(' ',#name))) AS f(Mid)
) AS f(FName,LName)
CROSS APPLY (VALUES (CHARINDEX(f.FName,t.CustomerName), CHARINDEX(f.LName,t.CustomerName))) AS pos(F,L)
WHERE (#partialmatch = 0 AND pos.F*pos.L > 0)
OR (#partialmatch = 1 AND pos.F+pos.L > 0);
When #partialmatch = 1 you get:
CustomerName FNMatch LNMatch
------------------------------ ----------- -----------
Johny Smith 1 1
Mr. Smithers 0 1
Johnathan Smithe 1 1
Setting #partialMatch to 0 will exclude "Mr. Smithers".

How to retrieve the matched word Text Search

How to retrieve the word text search rows. For example, if I search input as 'water Bottel', I need an output like 'Water Soap Bottel','Water Milk Bottel','Water Copper Bottel'. I know how to use LIKE Operator.
IF OBJECT_ID('tempdb..#SearchText') IS NOT NULL
DROP TABLE #SearchText
CREATE TABLE #SearchText
(
ProductId INT,
ProductName VARCHAR(500)
)
INSERT INTO #SearchText VALUES
(1,'Water Soap Bottel'),
(2,'Water Milk Bottel'),
(3,'Wooden Box'),
(4,'Water Plastic Bottel'),
(5,'Water Copper Bottel')
You can do this:
DECLARE #SearchTerm VARCHAR(100) = 'water bottel'
SELECT *
FROM #SearchText
WHERE ProductName LIKE '%' + REPLACE(#SearchTerm, ' ', '%') + '%'
However if you need to also return a row containing the phrase bottel water, the order of those words will mean the above doesn't work. In that case you will need to break up the query into multiple words, for example:
SELECT *
FROM #SearchText
WHERE ProductName LIKE '%water%'
AND ProductName LIKE '%bottel%'
If you have a full text index on that table, you could use CONTAINS:
SELECT *
FROM #SearchText
WHERE CONTAINS(ProductName, '"water" AND "bottel"')
You can split data on space and search if the splitted word match the splitted productname :
If all searched word must matches :
SELECT *
FROM #SearchText st
WHERE ( SELECT COUNT(value)
FROM STRING_SPLIT('water Bottel', ' ') ) = ( SELECT COUNT(*)
FROM STRING_SPLIT(st.ProductName, ' ') AS sv
JOIN STRING_SPLIT('water Bottel', ' ') AS ss
ON sv.value = ss.value )
If one or more word must match:
SELECT *
FROM #SearchText st
WHERE EXISTS ( SELECT 1
FROM STRING_SPLIT(st.ProductName, ' ') AS sv
JOIN STRING_SPLIT('water Bottel', ' ') AS ss
ON sv.value = ss.value )
Note : The string_split function is built-in on SQL Server 2016, you can search a create a custom implementation if you use a lower version.
Use LIKE operator.
SELECT
*
FROM #SearchText
WHERE LOWER(ProductName) LIKE '%water%'
AND LOWER(ProductName) LIKE '%bottel%'
You can ommit LOWER(...) function if collaction of column/database/server is case insensitive.

MSSQL query search with keyword list

I got one table that contains all information about products. I need to list all articles with a matching keywords (in this case the brand name) in a specific column. Is it possible to initiate some kind of a 'list' with all brand names that I can use for this operation? chaning OR for all brands seems kinda bad.
In the second step I only need to see all articles that does not contain a specific word order before they keywords from the first step.
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] like '%' + #brand +'%' AND [XWebtexke] NOT LIKE '%suited for%'
GO
Thats what I got so far, but it does not work in the way I need it.
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
select * from (
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] NOT LIKE '%suited for%' )t4
WHERE [XWebtexke] like '%' + #brand +'%'
GO
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
select * from (
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] NOT LIKE '%suited for%' )t4
WHERE t4.[XWebtexke] like '%' + #brand +'%'
GO
Realized you need all the keywords to match. Here is the solution for that.
You need to split the brand variable, try this:
DECLARE #brand NVARCHAR(200) = 'bmw, toyota, mercedes'
;WITH CTE as
(
SELECT '%'+ t.c.value('.', 'VARCHAR(2000)')+'%' val
FROM (
SELECT x = CAST('<t>' +
REPLACE(#brand, ', ', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)
)
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE
not exists(SELECT * FROM CTE WHERE [XWebtexke] not like val)
and [XWebtexke] NOT LIKE '%suited for%'
I am assuming there is always a space after the comma, you can adjust the code with ease if that is not always the case.
In sqlserver 2016 you can use STRING_SPLIT instead of the split used in my answer

SQL Select Statement LIKE IN

I need to write a select statement which returns a list of users where a list of SenderSubIDs exist in a field called constraint_values:
I need a LIKE IN statement ideally:
SELECT SenderSubID FROM fix_user_subids WHERE SenderSubID IN ('**00390529MGERAN1**','**00912220PBALDIS**','**03994113LDAMBRO**','**04004308SLOMBAR**','**04935278CARELLI**','**4004308SLOMBARD**')
SELECT * FROM fix_dyno_rule_defs WHERE constraint_values LIKE '%**00390529MGERAN1**%'
Returns:
rule_def_id tag msg_type required constraint_values constraint_type data_type default_value validation_type trans_type attribute_tag trans_tag memo
99800 10000 D,F,G 0 ((50,4,1,00390529MGERAN1)or(50,4,1,00912220PBALDIS)or(50,4,1,03994113LDAMBRO)or(50,4,1,04004308SLOMBAR)or(50,4,1,04935278CARELLI)or(50,4,1,4004308SLOMBARD))and(21,4,1,3)#STROP1#addattr(EQD,EQST) 0 1 #TAG=6506# 12 1800 0 0 Set EQD=1 for Equity Desk
I wrote this:
SELECT * FROM fix_dyno_rule_defs WHERE constraint_values LIKE '%' + (SELECT MAX(SenderSubID) FROM fix_user_subids WHERE SenderSubID IN ('00390529MGERAN1','00912220PBALDIS','03994113LDAMBRO','04004308SLOMBAR','04935278CARELLI','4004308SLOMBARD')) +'%'
But need it without the MAX as there is a list...
You don't get your ideal. Use or:
SELECT SenderSubID
FROM fix_user_subid
WHERE SenderSubID like '%00390529MGERAN1%' OR
SenderSubID like '%00912220PBALDIS%' OR
SenderSubID like '%04004308SLOMBAR%' OR
SenderSubID like '%04935278CARELLI%' OR
SenderSubID like '%4004308SLOMBARD%'
/This should help you try this
declare a temp table and store all the IDs in it/
declare #tempSenderIDs Table(
T_TableID varchar(10)
)
insert into #tempSender
(
T_TableID
)
values
select
senderSubID
from
SenderSubIDs
/final result will come from here/
select
f.SenderSubIDs
from
fix_user_subid f
where
s.ConstraintValue like '%' + (select T_TableID from #tempSenderIDs) +'%'
If I'm reading your question right (and I might not be!) you're looking to get results from the table fix_dyno_rule_defs.
In which case, can't you just do a simple join?
ie:
SELECT DISTINCT fdrd.*
FROM fix_dyno_rule_defs fdrd
JOIN fix_user_subid fus
ON fdrd.constraint_values LIKE '%' + REPLACE(fus.SenderSubID, '*','') + '%'
WHERE fus.SenderSubID IN ('**00390529MGERAN1**','**00912220PBALDIS**',
'**03994113LDAMBRO**','**04004308SLOMBAR**',
'**04935278CARELLI**','**4004308SLOMBARD**')