Tenho um cenário em que precisamos ativar uma pesquisa com várias palavras-chave em um campo de texto. Esta pesquisa deve envolver a verificação das palavras-chave em várias colunas (aproximadamente 4-6) em várias tabelas (atualmente 2 tabelas).
Problema, posso construir a consulta com operadores simples "AND" "OR"
Consulta na tentativa 1: retornar mais saída do que o necessário
Consulta na tentativa 2: retornar registro zero na saída
SAÍDA obrigatória: é a única primeira linha da saída da tentativa 1
-- truncate table #Customer -- truncate table #FaxDocs
-- Criação de Tabela
CREATE tABLE #FaxDocs ( [FaxDocID] INT , CustID INT, RemoteCSID VARCHAR(20), CSFileName VARCHAR(200)) INSERT INTO #FaxDocs SELECT 1,1,'123ag','257831.PDF' UNION ALL SELECT 2,1,'123yg','257837.PDF' UNION ALL SELECT 3,2,'123g','257838.PDF' UNION ALL SELECT 4,3,'123lg','257839.PDF' UNION ALL SELECT 5,4,'123CK','257840.PDF' CREATE TABLE #Customer ( CustID INT , CFNAME VARCHAR(20), CLNAME VARCHAR(200)) insert into #Customer SELECT 1,'ABCNJSGHK', 'CDE' UNION ALL SELECT 2,'CNJSGHK', 'CDE' UNION ALL SELECT 3,'FGH', 'IJK' UNION ALL SELECT 4,'LMN', 'OPQ'
--- Palavra-chave da barra de pesquisa
DECLARE @Search VARCHAR(MAX) = 'NJSGHK 257831.PDF' --CREATE TABLE #WordsToLookUp (Item VARCHAR(257), Location INT, Sequence INT PRIMARY KEY) INSERT INTO #WordsToLookUp(Item,[Location],[Sequence]) SELECT 'NJSGHK',0,1 UNION ALL SELECT '257831.PDF',8,2 ---------------------------------------------------------- SELECT * FROM #WordsToLookUp --truncate table #WordsToLookUp --- Attempt 1 SELECT [FaxDocID], Customer.CustID ,ISNULL(Customer.CFNAME,'') AS [FName], ISNULL(Customer.CLNAME,'') AS [LName] , Faxes.CSFileName FROM #FaxDocs Faxes LEFT JOIN #Customer Customer ON Faxes.CustID = Customer.CustID left join #WordsToLookUp B on Customer.CFNAME like '%'+ b.item+'%' left join #WordsToLookUp c on Customer.CLNAME like '%'+ c.item+'%' left join #WordsToLookUp d on Faxes.RemoteCSID like '%'+ d.item+'%' left join #WordsToLookUp e on Faxes.CSFileName like '%'+ e.item+'%' WHERE Faxes.[FaxDocID] in (1,2,3,4) -- Attempt 2 SELECT [FaxDocID], Customer.CustID ,ISNULL(Customer.CFNAME,'') AS [FName], ISNULL(Customer.CLNAME,'') AS [LName] , Faxes.CSFileName FROM #FaxDocs Faxes LEFT JOIN #Customer Customer ON Faxes.CustID = Customer.CustID WHERE Faxes.[FaxDocID] in (1,2,3,4) and exists (select 1 from #WordsToLookUp b where Customer.CFNAME like '%'+ b.item+'%') and exists (select 1 from #WordsToLookUp c where Customer.CLNAME like '%'+ c.item+'%') and exists (select 1 from #WordsToLookUp d where Faxes.RemoteCSID like '%'+ d.item+'%') and exists (select 1 from #WordsToLookUp e where Faxes.CSFileName like '%'+ e.item+'%')