Domanda

I have searched many answers, but I have not found a solution for the following simple task:

I have a lengthy TextString and want to look for an exact match to the string ' Text ' within it.

TextString LIKE '% Text %'

gives all occurrences of 'text' and 'Text', also starting and/or ending within a word. I want only occurrences of ' Text ' (case sensitive) with a preceding and trailing ' '.

I know the behaviour of LIKE and = with respect to SPACES, so there is no need to explain this again as it has been done elsewhere on this site.

È stato utile?

Soluzione 2

Try this:

Test data.

declare @t table (word nvarchar(50))

insert into @t
values (' text '), (' Text '), ('text '), (' text'), (' other '), (' text in large string'), ('xxxxxtext'),('xxxxxtext '), ('xxxx text') string')

Relevant query.

select * from @t

where word like '%' + ' text ' + '%'

Returns:

 text 
 Text 
 text in large string

Altri suggerimenti

Are you specifically asking about Microsoft SQL Server? If so...

The behaviour of the 'Like' comparison depends on how you have set up collation for your database (or table). If you have a case sensitive collation, then 'Like' will behave in a case sensitive way.

It is possible to override this behaviour on a case-by-case basis however:

SELECT MyField FROM MyTable 
WHERE MyField COLLATE Latin1_General_CS_AS LIKE '% Text %';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top