SqlServer: Like vs. “=” for matching strings
Whenever I write a stored procedure for selecting data based on string variable (varchar, nvarchar, char) I would have something like:
procedure dbo.p_get_user_by_username( @username nvarchar(256) as begin select u.username ,u.email --,etc from sampleUserTable u where u.username = @username end
So in other words to match the record I would have
u.username = @username
But sometimes I come across code that would use LIKE in place of =
When would you use it? Shouldn't that be used only when you need some wildcard matching?
Thanks for the answers.
I think that I need to clarify that what I was really trying to ask was: if there could be a situation when it was preferred to use like in place of "=" for exact string matching. From the answers I could say that there would not be. From my own experience even in situations when I need to ignore e.g case, and leading and ending spaces i would use ltrim, rtrim, lower on both strings and then "=". Thanks again for your input.
You are correct. There is no benefit in using LIKE unless you are doing wild card matching. In addition, using it without wildcard could lead to the use of an inefficient queryplan.