Check if string doesn't contain another string

Sql ServerTsqlString

Sql Server Problem Overview


In T-SQL, how would you check if a string doesn't contain another string?

I have an nvarchar which could be "Oranges Apples".

I would like to do an update where, for instance, a columm doesn't contain "Apples".

How can this be done?

Sql Server Solutions


Solution 1 - Sql Server

WHERE NOT (someColumn LIKE '%Apples%')

Solution 2 - Sql Server

Or alternatively, you could use this:

WHERE CHARINDEX(N'Apples', someColumn) = 0

Not sure which one performs better - you gotta test it! :-)

Marc

UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.

Solution 3 - Sql Server

Use this as your WHERE condition

WHERE CHARINDEX('Apples', column) = 0 

Solution 4 - Sql Server

The answers you got assumed static text to compare against. If you want to compare against another column (say, you're joining two tables, and want to find ones where a column from one table is part of a column from another table), you can do this

WHERE NOT (someColumn LIKE '%' || someOtherColumn || '%')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDofsView Question on Stackoverflow
Solution 1 - Sql ServerDaniel A. WhiteView Answer on Stackoverflow
Solution 2 - Sql Servermarc_sView Answer on Stackoverflow
Solution 3 - Sql ServerdutchView Answer on Stackoverflow
Solution 4 - Sql ServerGreg DoughertyView Answer on Stackoverflow