2015-05-02 10 views
9

Ho una squadra tavoloSQL SELECT testo simile

Id Name ... 
1 Chelsea 
2 Arsenal 
3 Liverpool 

Ora ho bisogno di cercare se la mia tabella di squadra ha un nome come "Chelsea FC". Come posso fare una query di selezione in questo caso quando la stringa di ricerca potrebbe contenere parole extra?

Potrei provare Lucene.net ma è un po 'eccessivo per un piccolo utilizzo e ci vorrebbe del tempo per impararlo.

risposta

9

Dovresti dividere la stringa in alto e cercare ogni parola nella stringa. SQL Server non ha una funzione nativa per farlo, ma ci sono vari esempi sul web.

Questa funzione prenderà una stringa e un delimitatore e dividerà la stringa del delimitatore e restituirà una tabella dei valori risultanti.

CREATE FUNCTION dbo.SplitVarchar (@stringToSplit varchar(4000), @delimiter CHAR(1)) 
RETURNS @Result TABLE(Value VARCHAR(50))AS 
BEGIN 
    --This CTE will return a table of (INT, INT) that signify the startIndex and stopIndex 
    --of each string between delimiters. 
    WITH SplitCTE(startIndex, stopIndex) AS 
    (
     SELECT 1, CHARINDEX(@delimiter, @stringToSplit) --The bounds of the first word 
     UNION ALL 
     SELECT stopIndex + 1, CHARINDEX(@delimiter, @stringToSplit, stopIndex+1) 
     FROM SplitCTE    --Recursively call SplitCTE, getting each successive value 
     WHERE stopIndex > 0 
    ) 

    INSERT INTO @Result 
    SELECT 
     SUBSTRING(@stringToSplit, --String with the delimited data 
      startIndex,    --startIndex of a particular word in the string 
      CASE WHEN stopIndex > 0 THEN stopIndex-startIndex --Length of the word 
      ELSE 4000 END --Just in case the delimiter was missing from the string 
      ) AS stringValue 
    FROM SplitCTE 

    RETURN 
END; 

Una volta che si accende la stringa delimitata in una tabella, si può aderire con la tabella che si desidera cercare e confrontare i valori in questo modo.

DECLARE @TeamName VARCHAR(50)= 'Chelsea FC' 

SELECT DISTINCT Name 
FROM Team 
INNER JOIN (SELECT Value FROM dbo.SplitVarchar(@TeamName, ' ')) t 
    ON CHARINDEX(t.Value, Name) > 0 

Risultati:

| Name | 
|---------| 
| Chelsea | 

SQL Fiddle example

ho basato il mio disegno sulla Amit Jethva di Convert Comma Separated String to Table : 4 different approaches

+2

Questo è impressionante – potashin

+1

Grazie, avevo fatto una recensione per una domanda simile che è stata chiusa (a causa della scarsa formulazione) prima che potessi rispondere. Fortunatamente, ho salvato il mio lavoro. :) –

+0

Questa è una soluzione di overkill. –

2

È possibile utilizzare like in questo modo:

declare @s varchar(20) = 'Chelsey FC' 

select * from Team 
where name like '%' + @s + '%' or 
     @s like '%' + name + '%' 

Ciò filtrare le righe se @s contiene Name o Name contiene @s.