T-SQL and the WHERE LIKE %Parameter% clause
Asked Answered
S

3

111

I was trying to write a statement which uses the WHERE LIKE '%text%' clause, but I am not receiving results when I try to use a parameter for the text. For example, this works:

SELECT Employee WHERE LastName LIKE '%ning%'

This would return users Flenning, Manning, Ningle, etc. But this statement would not:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%@LastName%'

No results found. Any suggestions?

Sinful answered 9/1, 2013 at 14:45 Comment(0)
E
211

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'
Enchant answered 9/1, 2013 at 14:46 Comment(5)
thanks for the earlier tip on the question. But it wasn't though. Anyway in the quest of a high performing answer - is this useful or not? :)Krenek
@Krenek I don't know really, performance and optimization is not my area. Furthermore, these functions are vendor specific, in your case it depends on how the Oracle RDBMS evaluate them, and I don't know Oracle. Sorry.Enchant
This didn't work for me. The % needs to be in the addParameter section. See James Curran answer here #251776Maximalist
see my answer (currently below). the wildcard-symbol is PART of the SEARCH expression, not part of the sql-query. It is entered by the USER (or, if wildcard-search is predefined, is appended to the users search expression input). If you append it via string concatanation on database-level, you get an unreusable query-stringAssurgent
This does not works correctly. Try two cases, one with hard-coded value after the like clause and another with parameter concat. Both fetching diff sets of results.Ronn
S
20

you may try this one, used CONCAT

WHERE LastName LIKE Concat('%',@LastName,'%')
Seacock answered 31/7, 2017 at 7:19 Comment(0)
A
18

The correct answer is, that, because the '%'-sign is part of your search expression, it should be part of your VALUE, so whereever you SET @LastName (be it from a programming language or from TSQL) you should set it to '%' + [userinput] + '%'

or, in your example:

DECLARE @LastName varchar(max)
SET @LastName = 'ning'
SELECT Employee WHERE LastName LIKE '%' + @LastName + '%'
Assurgent answered 2/6, 2015 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.